var apptManagement;
(function (apptManagement) {
    var Ares3ApptManagementGroupPage = /** @class */ (function () {
        function Ares3ApptManagementGroupPage(appNav) {
            var _this = this;
            this.appNav = appNav;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\" style=\"height: calc(100vh - 58px)\">\n                <ares-tab states=\"states\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope) {
                //scheduleCenter.add(new NavItem('scheduleCenter.groupCalendar', '预约视图', 'icon-puzzle', 'scheduleCenter.calendar'));
                //scheduleCenter.add(new NavItem('apptMgmt.groupApptList', '预约查询', 'icon-puzzle', 'scheduleCenter.search', true, { isCreateTime: false }));
                //scheduleCenter.add(new NavItem('apptMgmt.apptList', '预约查询', 'icon-puzzle', 'scheduleCenter.search', true, { isCreateTime: false }));
                //'apptMgmt.weixinApplyList', '网络预约', 'icon-puzzle', 'scheduleCenter.weixinApplyList'
                var TabItem = _this.appNav.TabItem;
                $scope.states = [
                    new TabItem('newGroupScheduleCenter.groupCalendar', '预约视图', '', 'scheduleCenter.calendar'),
                    new TabItem('newGroupScheduleCenter.apptList', '预约查询', '', 'scheduleCenter.calendar', null, null, false, '', false, { isCreateTime: false }),
                    new TabItem('newGroupScheduleCenter.applyList', '网络预约', '', 'scheduleCenter.calendar', null, null, false, '', false, { isCreateTime: false }),
                ];
            };
        }
        Ares3ApptManagementGroupPage.$inject = ['appNav'];
        return Ares3ApptManagementGroupPage;
    }());
    patientManagementModule.directive('ares3ApptManagementGroupPage', Ares.tsDirective(Ares3ApptManagementGroupPage));
})(apptManagement || (apptManagement = {}));

var ehr;
(function (ehr) {
    "use strict";
    var Ares3EhrManagementHomeView = /** @class */ (function () {
        function Ares3EhrManagementHomeView() {
            this.restrict = 'E';
            this.templateUrl = '/app-ares3/ehr/ehr-management-home/ares3-ehr-management-home-view.html';
            this.controller = 'Ares3EhrManagementHomeCtrl';
        }
        Ares3EhrManagementHomeView.$inject = [];
        return Ares3EhrManagementHomeView;
    }());
    ehrModule.directive('ares3EhrManagementHomeView', Ares.tsDirective(Ares3EhrManagementHomeView));
})(ehr || (ehr = {}));

var ehr;
(function (ehr) {
    'use strict';
    var Ares3EhrManagementHomeCtrl = /** @class */ (function () {
        function Ares3EhrManagementHomeCtrl($scope, appNav) {
            this.$scope = $scope;
            this.appNav = appNav;
            $scope.states = [
                new this.appNav.TabItem('ehrManagement.medicalExamCategory', '检查大类', '', 'medicalExam.category'),
                new this.appNav.TabItem('ehrManagement.medicalExamProject', '检查项目', '', 'medicalExam.item'),
                new this.appNav.TabItem('ehrManagement.medicalExamList', '检查申请', '', 'medicalExam.applicationList'),
            ];
        }
        Ares3EhrManagementHomeCtrl.$inject = ['$scope', 'appNav'];
        return Ares3EhrManagementHomeCtrl;
    }());
    ehrModule.controller('Ares3EhrManagementHomeCtrl', Ares.tsController(Ares3EhrManagementHomeCtrl));
})(ehr || (ehr = {}));

frameworkModule.controller('Ares3AppCtrl', [
    '$log', '$modal', '$scope', '$state', '$rootScope', '$timeout', 'loginContext',
    'appNav', 'enums', 'dataDicSvc', 'permissionProvider', 'systemOptionSvc',
    'eventAggregator', 'userOptionSvc', 'aresDialog', 'tenantReportSvc', 'officeSvc',
    'messengerSvc', 'patientTabManager', 'tenantSvc', 'localCache',
    'moduleOptionProvider', 'userSvc', 'functionGuideProvider', '$injector', 'hebeBusinessPortal',
    'hebeAppNavPortal', 'officeOptionSvc',
    function ($log, $modal, $scope, $state, $rootScope, $timeout, loginContext,
              appNav, enums, dataDicSvc, permissionProvider, systemOptionSvc,
              eventAggregator, userOptionSvc, aresDialog, tenantReportSvc, officeSvc,
              messengerSvc, patientTabManager, tenantSvc, localCache,
              moduleOptionProvider, userSvc, functionGuideProvider, $injector, hebeBusinessPortal,
              hebeAppNavPortal, officeOptionSvc) {

        var isUserKicked = false;
        var isDraged = false;
        var tryCnt = 0;
        var maxTryCnt = 20;
        var navItemProvider = null;

        var logOff = function () {
            // window.location = 'login.html';
            Ares.logOff();
        };

        var goToTenantSetting = function () {
            appNav.goToTenantSetting();
        };

        var getNavItemProvider = function () {
            if (!navItemProvider) {
                navItemProvider = window.Ares3
                    ? $injector.get('ares3NavItemProvider')
                    : $injector.get('appNavItemProvider');
            }
            return navItemProvider;
        };

        var containerState = {
            isScheduleCenterVisible: false,
            isPatientCenterVisible: false,
            isPatientHostVisible: false,
            isDefaultVisible: true,
        };
        var stateChangeSuccessData = null;

        containerState.calculateDefaultState = function () {
            containerState.isDefaultVisible = !containerState.isScheduleCenterVisible
                && !containerState.isPatientCenterVisible && !containerState.isPatientHostVisible;
        };

        $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
            var isScheduleCenterVisible = $state.includes('scheduleCenter') || $state.includes('groupScheduleCenter');
            if (containerState.isScheduleCenterVisible != isScheduleCenterVisible) {
                containerState.isScheduleCenterVisible = isScheduleCenterVisible;
                eventAggregator.publish(eventAggregator.events.ScheduleCenterVisibleChanged, containerState.isScheduleCenterVisible);
            }
        });

        // 解决网络不佳时预约中心不显示的问题：在权限初始化前先处理预约中心的显示
        var registerEventsBeforePermission = function () {
            $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
                var isScheduleCenterVisible = $state.includes('scheduleCenter') || $state.includes('groupScheduleCenter');
                if (containerState.isScheduleCenterVisible != isScheduleCenterVisible) {
                    containerState.isScheduleCenterVisible = isScheduleCenterVisible;
                    eventAggregator.publish(eventAggregator.events.ScheduleCenterVisibleChanged, containerState.isScheduleCenterVisible);
                }
                //保存参数
                stateChangeSuccessData = {};
                stateChangeSuccessData.event = event;
                stateChangeSuccessData.toState = toState;
                stateChangeSuccessData.toParams = toParams;
                stateChangeSuccessData.fromState = fromState;
                stateChangeSuccessData.fromParams = fromParams;
            });
        };

        var registerEvents = function () {
            $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
                if (!fromState._hasConfirmed) {
                    event.preventDefault();
                    appNav.confirmLeave(event, toState, toParams, fromState, fromParams)
                        .then(function () {
                            appNav.confirmEnter(event, toState, toParams, fromState, fromParams);
                        });
                }
            });

            $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
                fromState._hasConfirmed = false;
                refreshPatientCenter();
            });
        };

        //刷新患者中心
        var refreshPatientCenter = function () {
            if (!$scope.permissionsLoaded || !stateChangeSuccessData) {
                setTimeout(refreshPatientCenter, 100);
            }
            var event = stateChangeSuccessData.event;
            var toState = stateChangeSuccessData.toState;
            var toParams = stateChangeSuccessData.toParams;
            var fromState = stateChangeSuccessData.fromState;
            var fromParams = stateChangeSuccessData.fromParams;
            stateChangeSuccessData = null;

            containerState.isPatientCenterVisible = $state.includes('patientCenter');
            var isPatientHostVisible = !$state.includes('patientCenter')
                && toState.name.indexOf('patient') == 0;
            // 如果沒有患者中心的权限，则不显示patientHost
            if (isPatientHostVisible) {
                var isPatientCenterAllowed = permissionProvider.isPatientCenterAllowed();
                isPatientHostVisible &= isPatientCenterAllowed;
            }
            if (containerState.isPatientHostVisible != isPatientHostVisible) {
                containerState.isPatientHostVisible = isPatientHostVisible;
                eventAggregator.publish(eventAggregator.events.PatientHostVisibleChanged, containerState.isPatientHostVisible);
            }
            containerState.calculateDefaultState();

            var hasPermission = toState.name === 'noPermssion';
            if (!hasPermission) {
                var navItemProvider = getNavItemProvider();
                // 如果有激活的导航菜单，则认为有权限访问当前state
                // 如果patient host可见，则检查具体patient模块的权限
                var hasActiveItem = navItemProvider.initNavItemState() || toState.name === 'new';
                if (containerState.isPatientHostVisible) {
                    navItemProvider.patientHost.isActive = true;
                    var patientHostFirstSubItem = navItemProvider.patientHost.subItems[0];
                    if (patientHostFirstSubItem && patientHostFirstSubItem.text === '患者管理') {
                        var allPatientMenu = patientHostFirstSubItem.subItems[0];
                        if (allPatientMenu.id === 'patientHost') {
                            allPatientMenu.isActive = true;
                            patientHostFirstSubItem.expanded = true;
                        }
                    }
                    navItemProvider.patientHost.isSingleMode = toState.url.indexOf('/signle/') > -1;
                    if (navItemProvider.patientHost.isSingleMode) {
                        navItemProvider.patientHost.patientId = $state.params.patientId;
                    }
                } else if (toState.name.startsWith('newPatientManagement')
                    || toState.name.startsWith('complaint')
                    || toState.name.startsWith('pttCenter')) {
                    // 处理新的患者中心
                    // navItemProvider.patientHost.isActive = true;
                    // navItemProvider.patientHost.subItems[0].isActive = true;
                } else {
                    navItemProvider.patientHost.isActive = false;
                }

                hasActiveItem |= navItemProvider.patientHost.isActive;
                hasPermission = hasActiveItem;
                if (navItemProvider.patientHost.isActive) {
                    hasPermission = toState.permissionCode === null
                        || permissionProvider.isAllowed(toState.permissionCode);
                }
                // hasPermission = toState.permissionCode === null
                //     || permissionProvider.isAllowed(toState.permissionCode);
            }
            if (!hasPermission && toState.name != 'openPlatformCenter') {
                $log.error('无权限访问' + toState.name);
                $timeout(function () {
                    appNav.goToState('noPermssion');
                }, 100);
                return;
            }
            // navItemProvider.initNavItemState();

            $rootScope.currentState = toState.name;

            if (toState.onActivated) {
                toState.onActivated();
            }

            appNav.onStateChanged(event, toState, toParams, fromState, fromParams);

            if (containerState.isPatientHostVisible) {
                if (patientTabManager.isEmpty() && !permissionProvider.isAllowed('patientCenter.allPatients')) {
                    //appNav.goToState('patientCenter.patientList.search');
                } else {
                    $timeout(function () {
                        var splitter = $('#patientHostContainer').find('.k-splitter');
                        if (splitter) {
                            kendo.resize(splitter);
                        }
                    }, 5);
                }
            }

            // 当路由跳转是以 /new/ 开头的，则不进行埋点处理
            if (!toState.url.startsWith('/new/')) {
                Ares.sensors.autotrackspa();
            }
        };

        var switchOffice = function () {
            var modalInstance = $modal.open({
                animation: true,
                backdrop: 'static',
                template: '<office-switch-view></office-switch-view>',
                controller: 'OfficeSwitchCtrl',
                size: 'sm',
            });
        };

        var changePwd = function (isHideCloseBtn) {
            var modalInstance = $modal.open({
                animation: true,
                backdrop: 'static',
                keyboard: false,
                template: '<user-password-edit-view></user-password-edit-view>',
                controller: 'UserPasswordEditCtrl',
                windowClass: 'small-dialog',
                size: 'sm',
                resolve: {
                    host: function () {
                        return {
                            id: loginContext.userId,
                            account: loginContext.userAccount,
                            isHideCloseBtn: isHideCloseBtn
                        };
                    }
                }
            });
        };

        var subscribeEvents = function () {
            eventAggregator.subscribe($scope, eventAggregator.events.OfficeChanged, onOfficeChanged);
            eventAggregator.subscribe($scope, eventAggregator.events.ApiErrorHappened, onApiErrorHappened);
            eventAggregator.subscribe($scope, eventAggregator.events.UserKicked, onUserKicked);
        };

        var onOfficeChanged = function (event, office) {
            if (office.id == loginContext.officeId) {
                $scope.currentOffice = _.clone(office);
                $scope.officeName = office.abbreviation || office.name;
            }
        };

        var onApiErrorHappened = function (event, args) {
            if (args.data.name == 'AppointmentOperationException'
                || args.data.name == 'AresBusinessException' || args.data.name == 'CssdException'
                || args.data.autoAlert) {
                aresDialog.info('系统提示', args.data.message);
            }
        };

        var onUserKicked = function (event, args) {
            if (!isUserKicked) {
                aresDialog.warn('警告', "当前帐号已经在另一个客户端登录，如需继续使用，您需要重新登录。").then(
                    function () {
                        logOff();
                    },
                    function () {
                        logOff();
                    });
            }
            isUserKicked = true;
        };

        var turnOnAliPay = function (event, args) {
            appNav.goToState('AliTurnOn.open');
        };

        var openMainConversation = function () {
            if ($rootScope.isNewWxEnabled && $rootScope.scrmChat) {
                //officeSvc.getXcrmAuthInfo().success(function (appId) {
                //    if (appId) {
                $rootScope.isShowWxWebChat = !$rootScope.isShowWxWebChat; //显示/隐藏 新微信聊天窗体
                if (!isDraged) {
                    initDrag();
                }
                $('.scrm-webchat-view').css({
                    'left': '50%',
                    'margin-left': '-525px',
                    'top': 0
                });
                //    } else {
                //        aresDialog.info('提示', '没有授权微信公众号。请先至SCRM完成授权');
                //    }

                //}).error(function () {
                //    aresDialog.info('提示', '没有授权微信公众号。请先至SCRM完成授权');
                //});

                Ares.sensors.track('AppTopBarEvent', {
                    'EventType': '微信'
                });
            }
        };

        var initDrag = function () {
            $timeout(function () {
                try {
                    $('.scrm-webchat-view').draggable(
                        { cancel: "#char_scrm,.scrm_close" }
                    );
                    isDraged = true;
                } catch (err) {
                    tryCnt++;
                    if (tryCnt > maxTryCnt) {
                        $log.log(err);
                    } else {
                        initDrag();
                    }
                }

            }, 200);
        };

        // 接收商城iframe指令：切换诊所、修改密码
        var initIframeCommand = function () {
            window.addEventListener('message', function (event) {
                if (!event || !event.data) {
                    return;
                }
                if (event.data.source !== 'etrade') {
                    return;
                }
                // console.log('etrade', event);
                switch (event.data.action) {
                    case 'switchOffice':
                        if ($scope.canSwitchOffice) {
                            switchOffice();
                        }
                        break;
                    case 'changePassword':
                        changePwd();
                        break;
                    case 'logout':
                        logOff();
                        break;
                    case 'customerService':
                        $scope.onWebchatClick();
                        break;
                    default:
                        break;
                }
            })
        };

        var init = function () {
            if (!dataDicSvc.officeDic) {
                dataDicSvc.initialize();
            }

            dataDicSvc.officeDic.load().then(function (offices) {
                loginContext.hasMultiOffices = offices.length > 1;
                $scope.canSwitchOffice = offices.length > 1 && !loginContext.isAdminOffice &&
                    (loginContext.isRoot || loginContext.offices.length > 1);
                var currentOffice = _.find(offices, function (office) {
                    return office.id == loginContext.officeId;
                });
                if (!currentOffice && loginContext.officeId == officeSvc.adminOffice.id) {
                    currentOffice = officeSvc.adminOffice;
                }
                onOfficeChanged(null, currentOffice);
                initIframeCommand();

                if (!window.location.hash || window.location.hash.length == 0 || window.location.hash == '#/default') {
                    // Show dashboard as default page
                    if (loginContext.officeEdition == enums.BusinessEdition.FreeSupplychain) {
                        appNav.goToState('supplychainReport');
                    } else if (loginContext.isAdminOffice) {
                        appNav.goToDashboard();
                    } else {
                        if (loginContext.officeType === 1) {
                            if (loginContext.isGroup && loginContext.dashboardType) {
                                appNav.goToDashboard();
                            } else {
                                    appNav.goToOperationReport();
                            }
                        } else if (loginContext.roleType == '公司管理员') {
                            if (loginContext.officeEdition == enums.BusinessEdition.Ultimate) {
                                appNav.goToState('reportCenter.patient.newPatient');
                            } else {
                                appNav.goToState('reportCenter.patient.summary');
                            }
                        } else if (loginContext.roleType == '诊所管理员') {
                            appNav.goToState('reportCenter.patient.summary');
                        } else if (loginContext.dashboardType) {
                            appNav.goToDashboard();
                        } else {
                            if (loginContext.isGroup) {
                                appNav.goToOperationReport();
                            } else {
                                appNav.goToEnterpriseCenter();
                            }
                        }

                        if ($scope.dashboardType) {
                            appNav.goToDashboard();
                        }
                    }
                }

            });
        };

        var checkUserSecurity = function () {
            if (moduleOptionProvider.isUserSecurityEnabled()) {
                userSvc.needChangePassword().success(function (result) {
                    if (result) {
                        changePwd(true);
                    }
                });
            }
        };


        var delayInit = function () {
            Ares.initLogOffUrl();
            messengerSvc.initConnection(true);

            tenantReportSvc.getRemainedTrialDays().success(function (remainedTrialDays) {
                //remainedTrialDays 不为null时,才是试用账号
                if (remainedTrialDays != null) {
                    $scope.remainedTrialDays = remainedTrialDays;
                    $scope.isShowRemainedTrialDays = true;
                }
            });
            checkUserSecurity();

            functionGuideProvider.loadFunctionGuides();
        };

        var initQimoClinetId = function () {
            var officeId = loginContext.officeId;
            var tenantId = loginContext.tenantId;
            return tenantId + '-' + officeId;
        };

        var loadQimoJS = function () {
            tenantSvc.GetTenantIsCustomizeOpen().then(function (isCustomizeOpen) {
                //if (!isCustomizeOpen.data) {
                //    var jsUrl = "//webchat.7moor.com/javascripts/7moorInit.js?accessId=61d45470-7d8f-11e7-9b99-9fef3987fec1&autoShow=false";
                //    Ares.Loader.loadJs(jsUrl);
                //}
                var jsUrl = "http://172.18.10.125:9091/SublimeText3Project/yayi/js/7moorInit.js?accessId=61d45470-7d8f-11e7-9b99-9fef3987fec1&autoShow=false";
                Ares.Loader.loadJs(jsUrl);
            });
        };

        var systemTool = function () {
            appNav.goToState('systemTool');
        };

        var switchOldVersion = function () {
            Ares.sensors.track('Ares2Ares3', {
                'Ares2Ares3Action': 'MenuToAres2',
            });
            userOptionSvc.setUserOption(userOptionSvc.userOptionKey.selectedVersion, '2.0').then(function () {
                window.location = '/';
            })
        };

        /**
         * 检查Ares3上线倒计时
         */
        var checkAres3CountDown = function () {
            systemOptionSvc.getSystemOption(systemOptionSvc.optionKeys.Ares2EndDate).then(function(endDate) {
                endDate = moment(endDate, 'YYYY-MM-DD');
                if (endDate.isValid()) {
                    var today = moment().startOf('d');
                    endDate = endDate.startOf('d');
                    var isJustEndDate = today.isSame(endDate, 'd');
                    var cache = localCache.getCache(localCache.keys.Ares3OpenBannerShowNoMore);
                    var showNoMore = cache.loadValue();
                    if (isJustEndDate && showNoMore !== '1') {
                        var ares3CountDownModal = $modal.open({
                            animation: true,
                            backdrop: 'static',
                            controller: 'Ares3CountDownDialogCtrl',
                            template: '<ares3-count-down-dialog-view></ares3-count-down-dialog-view>',
                            keyboard: false,
                            windowClass: 'ares3-count-down-dialog-wrapper-open',
                            resolve: {
                                host: function () {
                                    return {
                                        showFinalBanner: true
                                    }
                                }
                            }
                        });
                    }
                }
            });
        };

        /**
         * 深圳卫监医生人脸识别
         */
        var checkShenzhenHealthFaceRecognition = function () {
            if (loginContext.providerJob === '医生') {
                officeOptionSvc.getOfficeOption(officeOptionSvc.optionKeys.IsHealthBureauDataExportEnabled_Shenzhen).then(function (isEnable) {
                    if (isEnable) {
                        var faceDialog = $modal.open({
                            animation: true,
                            backdrop: 'static',
                            controller: 'ShenzhenFaceRecognitionDialogCtrl',
                            template: '<shenzhen-face-recognition-dialog></shenzhen-face-recognition-dialog>',
                            windowClass: 'shenzhen-health-face-recognition-window',
                            keyboard: false,
                            resolve: {
                                host: function () {
                                    return {
                                    };
                                }
                            }
                        });

                        faceDialog.result.then(function (shouldLogOff) {
                            if (shouldLogOff) {
                                Ares.logOff();
                            }
                        });
                    }
                });
            }
        };

        /**
         * 每天定时登出
         */
        var startAutoLogOutTimer = function () {
            var checkLogout = function () {
                var lastLoginCache = localCache.getCache(localCache.keys.LastLoginTime);
                var lastLoginTime = parseInt(lastLoginCache.loadValue());
                if (lastLoginTime && moment(lastLoginTime).diff(moment(), 'hour') <= -18) {
                    lastLoginCache.clear();
                    Ares.logOff();
                }
            }
            checkLogout();
            setInterval(checkLogout, 60 * 60 * 1000);
        };

        (function initialize() {
            //启用了SSO登录后初始化
            try {
                var ssoNav = $injector.get('ssoNav');
                if (ssoNav) {
                    ssoNav.init();
                }
            } catch (e) {

            }

            $rootScope.isWxClinic = false;
            $scope.isInitialized = false;
            $scope.containerState = containerState;
            $scope.$state = $state;
            $scope.logOff = logOff;
            $scope.goToTenantSetting = goToTenantSetting;
            //支付宝活动事件
            $scope.turnOnAliPay = turnOnAliPay;
            //聊天框事件
            $scope.openMainConversation = openMainConversation;

            $scope.login = loginContext;
            $scope.canSwitchOffice = false;
            $scope.switchOffice = switchOffice;
            $scope.changePwd = changePwd;
            $scope.systemTool = systemTool;
            $scope.hasTenantSettingPermission = false;
            $scope.remainedTrialDays = "";
            $scope.isShowRemainedTrialDays = false;

            $scope.$root.isRegularChain = loginContext.isRegularChain;
            $scope.$root.officeId = loginContext.officeId;
            $scope.$root.isTenantAdmin = loginContext.isTenantAdmin;
            $scope.$root.containerState = containerState;

            subscribeEvents();
            registerEventsBeforePermission();
            hebeBusinessPortal.init();
            hebeAppNavPortal.init();

            permissionProvider.loadPermissions().then(function () {
                patientTabManager.initialize();
                var navItemProvider = getNavItemProvider();
                navItemProvider.initialize().then(function () {
                    initMakeTemplate();

                    registerEvents();
                    dataDicSvc.initialize();
                    userOptionSvc.load();

                    $scope.hasTenantSettingPermission = permissionProvider.isAllowed('tenantSettings');
                    $scope.isInitialized = true;
                    $scope.$root.isInitialized = true;
                    eventAggregator.publish('appInitialized');
                    $scope.permissionsLoaded = true;
                    if (stateChangeSuccessData) {
                        refreshPatientCenter();
                    }
                });
            });

            $timeout(function () {
                init();
            }, 500);

            $timeout(function () {
                delayInit();
            }, 1000);

            window.onunload = function (e) {
                Ares.logOff(true);
            };

            checkAres3CountDown();
            startAutoLogOutTimer();
            checkShenzhenHealthFaceRecognition();

            $scope.qimoClientId = initQimoClinetId();
            $scope.loadQimoJS = loadQimoJS;
            $scope.switchOldVersion = switchOldVersion;
            $scope.canReturnAres2 = !moduleOptionProvider.isAres2Disabled();
        })();
    }]);

ares3Module.service('ares3NavItemProvider', [
    '$log', '$state', '$q', '$rootScope', 'loginContext', 'permissionProvider', 'moduleOptionProvider', 'dashboardSvc',
    'officeOptionSvc', 'officeUtil', 'localCache', 'enums', 'dataDicSvc', 'systemConfigSvc',
    function ($log, $state, $q, $rootScope, loginContext, permissionProvider, moduleOptionProvider, dashboardSvc,
        officeOptionSvc, officeUtil, localCache, enums, dataDicSvc, systemConfigSvc) {
        'use strict';

        // 高级报表配置
        var reportSetConfigs;
        // 是否打开检查
        var isMedicalExamOpen;
        // 是否启用领健CRM
        var isLcCrmEnabled;
        // 是否已升级至新支付方式（新报表）
        var isPaymentTypeUpgradeFinished;
        // 是否初始即新支付方式
        var isPaymentTypeUpgradeInitialized;

        var NavItem = function (id, text, className, permissionCode, isVisible, param) {
            this.id = id;
            this.text = text;
            this.className = className || 'icon-puzzle';
            this.permissionCode = (permissionCode != undefined && permissionCode != '') ? permissionCode : id;
            this.isVisible = isVisible != undefined ? isVisible : true;
            this.isActive = false;
            this.parent = null;
            this.subItems = null;
            this.allowedSubItems = null;
            this.hasVisibleSubItem = false;
            this.param = param != undefined ? param : null;
            this.allowAnoymous = permissionCode === null;
            this.expanded = false;
            this.lastVisitedChild = null;
        };

        NavItem.prototype = {
            add: function (subItem) {
                subItem.parent = this;
                if (this.subItems == null) {
                    this.subItems = [];
                }
                this.subItems.push(subItem);
                // 默认展开
                // this.expanded = true;
            },
            addBatch: function (subItems) {
                var currentItem = this;
                angular.forEach(subItems, function (subItem) {
                    currentItem.add(subItem);
                });
                // this.expanded = true;
            },
            setAllowedSubItem: function (allowedSubItems) {
                this.allowedSubItems = allowedSubItems.length > 0 ? allowedSubItems : null;
                if (this.allowedSubItems == null || this.allowedSubItems.length == 0) {
                    if (this.allowAnoymous) {
                        this.isVisible = true;
                    } else if (this.subItems != null && this.subItems.length > 0) {
                        // If has sub item, but no sub is item visible, then this menu is not visible.
                        this.isVisible = false;
                    } else {
                        this.isVisible = isNavItemAllowed(this);
                    }
                }
                if (this.allowedSubItems) {
                    this.hasVisibleSubItem = this.allowedSubItems.some(function (item) {
                        return item.isVisible;
                    });
                }
            }
        };

        var createDashboard = function () {
            //if (loginContext.dashboardType === 'FrontDesk') {
            //    return new NavItem('new', '我的工作', 'iconfont icon-wodegongzuo', null, true, { route: 'workbench' });
            //}
            if (loginContext.dashboardType === 'Inventory') {
                return new NavItem('new', '我的工作', 'iconfont icon-wodegongzuoA', null, true, { route: 'supplychain.dashboard' });
            }
            return new NavItem('dashBoard', '我的工作', 'iconfont icon-wodegongzuoA', null);
        };

        // 患者中心
        var createPatientHost = function () {
            var patientHost = new NavItem('', '患者中心', 'iconfont icon-huanzhezhongxinA', '^');
            var subItems = [];
            // 患者管理
            var patientManagement = new NavItem('', '患者管理', '', '^');
            var patientManagementItems = [];
            patientManagementItems.push(new NavItem('patientHost', '所有患者', '', 'patientMgmt.browse|patientMgmt.heathInsurance|patientMembership.browse|patientCharge.history|patientMgmt.apptRecord|patientMgmt.diagnoseRecord|patientMgmt.txplan|patientMgmt.consultRecord|patientMgmt.orthdontic|patientMgmt.revisitRecord|patientImaging.list|patientDocument.list|generalExam.history|perioExam.history|patientFollowup.history|patientOutProcess.history|patientPrescription.history|patientLisOrder.history|patientMedicalRecord.list|dataImport.patient'));
            patientManagementItems.push(new NavItem('newPatientManagement.duplicate', '重复患者', '', 'patientCenter.duplicatedPatient'));
            // patientManagementItems.push(new NavItem('newPatientManagement.archived', '归档患者', '', 'patientCenter.archivedPatient'));
            patientManagementItems.push(new NavItem('newPatientManagement.import', '患者导入', '', 'dataImport.patient'));
            patientManagement.addBatch(patientManagementItems);
            subItems.push(patientManagement);
            subItems.push(new NavItem('newPatientManagement.followup', '随访管理', '', 'followup.list|followup.last'));
            subItems.push(new NavItem('complaint', '投诉管理', '', 'complaintManagement.list'));
            // subItems.push(new NavItem('pttCenter', '预检分诊', 'icon-puzzle', 'precheckTriage.view'));
            patientHost.addBatch(subItems);
            return patientHost;
        };

        var createScheduleCenter = function () {
            var scheduleCenter = new NavItem('new', '预约中心', 'iconfont icon-yuyuezhongxin1A', 'scheduleCenter.calendar|scheduleCenter.search|scheduleCenter.weixinApplyList', true, {
                route: 'appointment'
            });
            return scheduleCenter;
        };

        //供应链
        var createSupplychain = function () {
            //物品管理
            var productMgmt = new NavItem('supplychain.product', '基础信息', '', 'product.productInfo|product.supplierInfo|warehouse.warehouseManagement');
            //耗材追溯
            var traceabilityMgmt = new NavItem('supplychain.traceability', '耗材追溯', '', 'warehouse.warehouseManagement');
            //仓库管理
            var inventoryMgmt = new NavItem('supplychain.inventory', '仓库管理', '', 'inventoryBrowse.stockStatus|inventoryOperation.stockInBrowser|inventoryOperation.stockTransferBrowser|inventoryOperation.stockCheck|inventoryOperation.stockOutBrowser|warehouse.warehouseManagement');
            //采购管理
            var procurementMgmt = new NavItem('supplychain.procurement', '采购管理', '', 'procurement.procurementViewPayOrder|procurement.procurementViewAssistant|procurement.procurementManageOfficeApply|procurement.supplierSettlement');
            // 进销存 - 一级入口
            var supplychain = new NavItem('supplychain', '进销存', 'iconfont icon-kufangguanli');
            var subItems = [procurementMgmt];

            //当前诊所是否群组节点
            if (loginContext.isGroup) {
                //当前诊所是否开启库存管理
                if (moduleOptionProvider.isGroupInventoryEnabled()) {
                    subItems.push(inventoryMgmt);
                    subItems.push(traceabilityMgmt);
                }
                //当前诊所是根节点
                if (loginContext.isRootGroup) {
                    if (moduleOptionProvider.isInventoryTakeWorkflowEnabled()) {
                        subItems.push(new NavItem('supplychain.myApply', '领用管理', '', 'Application.fillApplication'));
                    }
                }
            } else {
                subItems.push(inventoryMgmt);
                if (moduleOptionProvider.isInventoryTakeWorkflowEnabled()) {
                    subItems.push(new NavItem('supplychain.myApply', '领用管理', '', 'Application.fillApplication'));
                }
                subItems.push(traceabilityMgmt);
            }
            //物品管理排最后
            subItems.push(productMgmt);
            //进销存报表
            subItems.push(new NavItem('supplychainReport', '进销存报表', '', 'supplychainReport.overview|supplychainReport.inventorySummary|supplychainReport.purchaseSummary|supplychainReport.takeSummary|supplychainReport.salesSummary|supplychainReport.SupplierSettlementHistory'));
            supplychain.addBatch(subItems);
            return supplychain;
        };

        // 报表中心
        var createReportCenter = function () {
            var reportCenter = new NavItem('', '报表中心', 'iconfont icon-baobiaozhongxin1A', '^');

            // 运营分析
            var operationReport = new NavItem('', '运营分析', '', '^');
            var operationItems = [
                new NavItem('reportCenter.patient', '患者分析', '', 'operation.patienttAnalysis|tenantReport.newPatients|operation.referrer|operation.patientSource|finance.patientConsumption'),
                new NavItem('reportCenter.appointment', '预约分析', '', 'operation.apptAnalysis|tenantReport.apptTrend|operation.patientAppt'),
                // new NavItem('reportCenter.marketing', '营销分析', '', 'operation.gift'),
                // new NavItem('reportCenter.revenue', '营收分析', '', 'operation.amounttAnalysis|tenantReport.incomeSummary|tenantReport.incomeTrend'),
                new NavItem('reportCenter.operation', '运营分析统计', '', 'operation.analysis'),
            ];
            operationReport.addBatch(operationItems);

            var reportCacheKey = localCache.getCacheKey(localCache.keys.IsNewFinanceReportEnabled, loginContext.officeId);
            var reportCache = localCache.getCache(reportCacheKey);

            var performanceReportCacheKey = localCache.getCacheKey(localCache.keys.IsNewPerformanceReportEnabled, loginContext.officeId);
            var performanceReportCache = localCache.getCache(performanceReportCacheKey);

            var isNewFinanceReportEnabled = isPaymentTypeUpgradeInitialized || (isPaymentTypeUpgradeFinished && !!reportCache.loadValue());
            var isNewPerformanceReportEnabled = isPaymentTypeUpgradeInitialized || (isPaymentTypeUpgradeFinished && !!performanceReportCache.loadValue());

            // 老版绩效中心
            var oldPerformance = new NavItem('performance', '绩效中心', '', 'performance.doctorChargeDetail|performance.doctorChargeCategroy|performance.doctorVisits|performance.nurseChargeDetail|performance.nurseChargeCategroy|performance.consultantChargeCategory|performance.consultantWorkSummary|performance.assistantWorkSummary|performance.doctorApptPerformance|performance.chargeDeduction|performance.medicalExam|performance.networkConsult|performance.apptTransferred', !isNewPerformanceReportEnabled);

            // 绩效管理
            var performance = new NavItem('performancev2', '绩效管理', '', '^', isNewPerformanceReportEnabled);
            var performanceItems = [];
            if (reportSetConfigs) {
                switch (loginContext.providerJob) {
                    case "医生":
                        performanceItems.push(new NavItem('performancev2.personalDoctorPerformanceSetV3', '我的绩效', '', 'performancev2.personalPerformanceReport|performancev2.personalDepartmentPerformanceReport'));
                        break;
                    case "护士":
                        performanceItems.push(new NavItem('performancev2.personalNursePerformanceSetV3', '我的绩效', '', 'performancev2.personalPerformanceReport|performancev2.personalDepartmentPerformanceReport'));
                        break;
                    case "咨询师":
                        performanceItems.push(new NavItem('performancev2.personalConsultPerformanceSetV3', '我的绩效', '', 'performancev2.personalPerformanceReport|performancev2.personalDepartmentPerformanceReport'));
                        break;
                    default:
                        break;
                }

                fillReportSet(performanceItems, 'performancev2.onlineConsultPerformanceSet', 'DashboardOnlineConsultPerformanceSet');
                fillReportSet(performanceItems, 'performancev2.departmentPerformanceSet', 'DepartmentPerformanceSet');
                fillReportSet(performanceItems, 'performancev2.doctorPerformanceSet', 'DoctorPerformanceSet');
                fillReportSet(performanceItems, 'performancev2.consultPerformanceSet', 'ConsultPerformanceSet');
                fillReportSet(performanceItems, 'performancev2.nursePerformanceSet', 'NursePerformanceSet');
                performanceItems.push(new NavItem('reportCenter.assistantWork', '牙医助理工作', '', 'performancev2.assistantWorkReport'));
                fillReportSet(performanceItems, 'performancev2.statementSearchSet', 'StatementSearchSet');
                if (isMedicalExamOpen) {
                    performanceItems.push(new NavItem('reportCenter.performance.medicalExam', '拍片绩效', '', 'performancev2.medicalExam'))
                }
            }
            performanceItems.push(new NavItem('reportCenter.apptPerformance', '预约绩效', '', 'performancev2.doctorApptPerformance'));
            performance.addBatch(performanceItems);

            // 老版财务中心
            var oldFinanceReport = new NavItem('finance', '财务中心', '', 'managementCenter.accountStatement|finance.checkCalendar|finance.everydayCheck|finance.officeChargeDetail|finance.chargeSummary|finance.chargeDetail|finance.chargeItemDetail|finance.overduePatient|finance.patientConsumption|finance.familyConsumption|finance.membershipSummary|finance.aliPayOrderTransaction|finance.weixinPayOrderTransaction|finance.cashFlow|finance.chargeGroupBuyCertificate|finance.membershipBalance|finance.chargeDiscount|finance.customizeReport|finance.yibaoAccountCheck', !isNewFinanceReportEnabled);
            // 财务对账
            var financeReport = new NavItem('financev2', '财务对账', '', '^', isNewFinanceReportEnabled);
            var financeReportItems = [];
            if (!loginContext.isGroup) {
                financeReportItems.push(new NavItem('reportCenter.financeCalendar', '对账日历', '', 'financev2.checkCalendar'));
            }
            if (reportSetConfigs) {
                fillReportSet(financeReportItems, 'financev2.dailyCheckActualPriceReportSetV3', 'DailyCheckActualPriceReportSet');
                fillReportSet(financeReportItems, 'financev2.netflowAmbassadorCheckSet', 'NetflowAmbassadorCheckSet');
                fillReportSet(financeReportItems, 'financev2.dailyCheckReportCashflowSet', 'DailyCheckReportCashflowSet');
                fillReportSet(financeReportItems, 'financev2.chargeAdvanceReportSet', 'ChargeAdvanceReportSet');
                fillReportSet(financeReportItems, 'financev2.dailyCheckReportBussinessIncomeSet', 'DailyCheckReportBussinessIncomeSet');
                // fillReportSet(financeReportItems, 'financev2.dealDetailReportSet', 'DealDetailReportSet');
                fillReportSet(financeReportItems, 'financev2.dealDetailReportSetV3', 'DealDetailReportSet');
                fillReportSet(financeReportItems, 'financev2.certificateReportSet', 'CertificateReportSet');
                fillReportSet(financeReportItems, 'financev2.membershipReportSet', 'MembershipReportSet');
                fillReportSet(financeReportItems, 'financev2.otherFinanceReportSet', 'OtherFinanceReportSet');
                fillReportSet(financeReportItems, 'financev2.overduePatientSet', 'OverduePatientSet');
            }
            //financeReportItems.push(new NavItem('reportCenter.overduePatient', '欠费患者', '', 'financev2.overduePatientReport'));
            financeReportItems.push(new NavItem('reportCenter.familyConsumption', '家庭消费统计', '', 'financev2.familyConsumptionRepot'));
            financeReport.addBatch(financeReportItems);

            // 填充报表中心菜单
            var reportCenterSubItems = [
                operationReport,
                // oldFinanceReport,
                financeReport,
                // oldPerformance,
                performance,
            ];
            if (!loginContext.isTenantAdmin && loginContext.dashboardRoleType !== '财务') {
                reportCenterSubItems.push(new NavItem('personalperformance', '个人绩效'));
            }
            // 根据配置决定是否显示定制报表
            if (moduleOptionProvider.isCustomMadeReportOpen()) {
                reportCenterSubItems.push(new NavItem('customMadeReport', '定制报表', '', 'customerMadeFolder.otherReport'));
            }

            reportCenterSubItems.push(new NavItem('reportCenter.mine', '报表下载', '', 'finance.myReport'));
            reportCenter.addBatch(reportCenterSubItems);
            return reportCenter;
        };

        // 营销中心
        var createMarketingManagement = function () {
            var marketing = new NavItem('', '营销中心', 'iconfont icon-yingxiaozhongxin', '^');
            var marketingItems = [];
            // 营销中心-微信营销
            if (moduleOptionProvider.isSCRMOpen()) {
                $rootScope.isNewWxEnabled = true;
                if (permissionProvider.isAllowed('scrmMgmt.loggin')) {
                    // marketingItems.push(new NavItem('scrmCenter', '微信营销', '', null));
                }
            }
            // 营销中心-卡券管理
            marketingItems.push(new NavItem('marketingManagement.giftCard', '卡券管理', '', 'membership.cardDetail|membership.discount|membership.publish|membership.giftCard'));
            // 营销中心-流量大使
            marketingItems.push(new NavItem('marketingManagement.appointmentChannel', '流量大使', '', 'setting.integration'));
            // 营销中心-会员管理
            marketingItems.push(new NavItem('marketingManagement.member', '会员管理', '', 'membership.list|membership.typeApply|membership.transaction'));
            // 营销中心-咨询管理
            marketingItems.push(new NavItem('newPatientManagement.consult', '咨询管理', '', 'consultCenter.list|consultCenter.consultList'));
            // 营销中心-推荐管理
            if (moduleOptionProvider.isReferralEnabled()) {
                var referral = new NavItem('marketingManagement.referral', '推荐管理', '', 'referralCenter.all');
                var referralItems = [];
                if (!loginContext.isGroup) {
                    referralItems.push(new NavItem('marketingManagement.referralSummary', '概览', '', null));
                }
                referralItems.push(new NavItem('marketingManagement.referralDetail', '推荐明细', '', null));
                referralItems.push(new NavItem('marketingManagement.referralReward', '推荐激励明细', '', null));
                referral.addBatch(referralItems);
                marketingItems.push(referral);
            }
            // 营销中心-回访管理
            marketingItems.push(new NavItem('newPatientManagement.revisit', '回访管理', '', 'ReturnVisitFolder.list'));
            // 营销中心-医患沟通视频
            marketingItems.push(new NavItem('medicalService.patientVideo', '医患沟通视频', '', 'pdCommunication.video'));
            // 营销中心-短信管理
            marketingItems.push(new NavItem('officeManagement.sms', '短信管理', '', 'shortMessage.list|shortMessage.history|shortMessage.batch|shortMessaage.reply|shortMessage.charge|shortMessage.statistics'));

            marketing.addBatch(marketingItems);

            return marketing;
        };

        // 技加工
        var createDentalManagement = function () {
            var dentalManagement = new NavItem('', "技加工", 'iconfont icon-weixiu', '^');
            var dentalManagementItems = [];
            if (moduleOptionProvider.isNewDentalLabEnabled()) {
                dentalManagementItems.push(new NavItem('dentalLab.orderTrack', '订单跟踪', '', 'dentalLab.order'));
                dentalManagementItems.push(new NavItem('dentalLab.settlement', '结算管理', '', 'dentalLab.order.completeSettle'));
                dentalManagementItems.push(new NavItem('dentalLab.product', '项目维护', '', 'dentalLab.product'));
                dentalManagementItems.push(new NavItem('dentalLab.import', '项目导入', '', 'dentalLab.product'));
                dentalManagementItems.push(new NavItem('dentalLab.factory', '厂商管理', '', 'dentalLab.factory'));
            } else {
                dentalManagementItems.push(new NavItem('outprocessCenter', '技加工', '', 'managementCenter.outprocess'));
            }
            dentalManagement.addBatch(dentalManagementItems);
            return dentalManagement;
        };

        // 诊所中心
        var createOfficeManagement = function (officeSetting) {
            var officeManagement = new NavItem('', '诊所中心', 'iconfont icon-zhensuoguanliA', '^');
            var officeManagementItems = [];

            // 医疗质控
            var medicalQuality = new NavItem('', '医疗质控', '', '^');
            var medicalQualityItems = [];
            if (moduleOptionProvider.isNewMedicalExamEnabled()) {
                medicalQualityItems.push(new NavItem('medicalExam', '检查管理', '', 'medicalExam.applicationList'));
            }
            medicalQualityItems.push(new NavItem('medicalrecordCenter', '病历管理', '', 'patientCenter.emrSearch'));
            if (loginContext.providerJob === '医生') {
                medicalQualityItems.push(new NavItem('pendingMedicalrecord', '待办病历', '', null));
            }
            medicalQuality.addBatch(medicalQualityItems);
            officeManagementItems.push(medicalQuality);

            //if (moduleOptionProvider.isNewDentalLabEnabled()) {
            //    // 技加工（新）
            //    officeManagementItems.push(new NavItem('dentalLab', '技加工（新）', '', 'dentalLab.order|dentalLab.product|dentalLab.factory'));
            //} else {
            //    officeManagementItems.push(new NavItem('outprocessCenter', '技加工', 'icon-puzzle', 'managementCenter.outprocess'));
            //}

            // 员工管理
            var subItems = [];
            subItems.push(new NavItem('officeManagement.staff', '员工管理', '', 'setting.provider|setting.role|setting.partnerUserManagement'));
            subItems.push(new NavItem('officeManagement.handover', '人员交接', '', 'setting.patientHandOver|setting.chargeDeductionHandOver'));
            subItems.push(new NavItem('officeManagement.schedule', '排班考勤', '', 'schedule.doctor|schedule.tenant|schedule.attendanceList'));
            if (moduleOptionProvider.isAppointmentResourceEnabled()) {
                subItems.push(new NavItem('officeManagement.appointmentResource', '号源管理', '', 'setting.providerResourceView|setting.appointmentResourceView'));
            }
            var providerManagement = new NavItem('', '员工管理', '', '^');
            providerManagement.addBatch(subItems);
            officeManagementItems.push(providerManagement);

            // 诊所管理
            subItems = [];
            subItems.push(new NavItem('officeManagement.businessRule', '审批管理', '', 'workflowManagement.approval'));
            // subItems.push(new NavItem('officeManagement.orgchain', '连锁管理', '', 'organizationManagement.baseData'));
            // subItems.push(new NavItem('expendCenter', '支出管理', '', 'expendCenter.list'));
            subItems.push(new NavItem('memo', '备忘管理', 'icon-puzzle', 'memoManagement.record'));
            if (isLcCrmEnabled) {
                //subItems.push(new NavItem('officeManagement.officeAccount', '诊所账户', 'glyphicon glyphicon-home', 'tenantSettings.account'));
                // subItems.push(new NavItem('officeManagement.accountAcceptance', '账户验收', 'glyphicon glyphicon-home', 'setting.accountAcceptance'));
            }
            if (moduleOptionProvider.isInvoiceEnabled()) {
                // subItems.push(new NavItem('invoiceCenter', '发票管理', '', 'invoice.mgmt'));
            }
            if (moduleOptionProvider.isHealthBureauDataExportEnabled() || moduleOptionProvider.isBizDataBackupEnabled() || moduleOptionProvider.isHealthBureauDataExportEnabled_Shenzhen()) {
                subItems.push(new NavItem('officeManagement.export', '数据管理', '', "dataExport.healthBureauDataExport|dataExport.bizDataBackup"));
            }
            var businessManagement = new NavItem('', '诊所管理', '', '^');
            businessManagement.addBatch(subItems);
            officeManagementItems.push(businessManagement);

            // 安全管理
            var securityMenu = new NavItem('', '安全管理', '', 'security.loginLog|security.dataSetting|security.operationLog|deviceSecurity.management|deviceSecurity.application');
            var securityMenuItems = [
                new NavItem('officeManagement.accountSecurity', '账号安全', '', 'security.loginLog'),
                new NavItem('officeManagement.patientSecurity', '患者数据', '', 'security.dataSetting'),
                new NavItem('officeManagement.operationSecurity', '操作日志', '', 'security.operationLog'),
            ];
            if (moduleOptionProvider.isDeviceMgmtEnabled()) {
                securityMenuItems.push(new NavItem('officeManagement.deviceSecurity', '设备安全', '', 'deviceSecurity.management|deviceSecurity.application'))
            }
            securityMenu.addBatch(securityMenuItems);
            officeManagementItems.push(securityMenu);



            // 填充诊所中心菜单
            officeManagement.addBatch(officeManagementItems);
            return officeManagement;
        };

        //CSSD
        var createCssd = function () {
            var cssd = new NavItem('cssd', 'CSSD', 'iconfont icon-cssd');
            var subItems = [
                new NavItem('cssd.baseData', '基础信息', '', null),
                //new NavItem('cssd.businessRules', '业务规则', '', null),
                new NavItem('cssd.businessCenter', '业务中心', '', null),
                //new NavItem('cssd.traceabilityTracking', '追溯跟踪', '', null),
                //new NavItem('cssd.effectMonitoring', '效果监测', '', null),
                new NavItem('cssd.borrowLog', '借入借出', '', null)
            ];
            cssd.addBatch(subItems);
            return cssd;
        };

        // 领健商城
        var createMallCenter = function () {
            var mallCenter = new NavItem('mallCenter', '领健商城', 'iconfont icon-youcaishangcheng', null);
            return mallCenter;
        };

        //增值服务
        var createOpenPlatformCenter = function () {
            var openPlatformCenter = new NavItem('new', '增值服务', 'iconfont icon-kaifangpingtai', null, true, {
                route: 'enterpriseCenter.services'
            });
            return openPlatformCenter;
        };

        // 系统设置
        var createSystemSetting = function () {
            var systemSetting = new NavItem('', '系统设置', 'iconfont icon-xitongshezhi1A', '^');

            var subItems = [
                // 通用设置
                new NavItem('systemSetting.officeManagementMisc', '通用设置', '', 'settings.rule|setting.systemsetting|setting.office|setting.operatory')
            ]

            // 收费设置
            var chargeMenu = new NavItem('', '收费设置', '', 'settings.chargeInfo|setting.chargeitemBrowse|settings.baseData|dataImport.chargeItem');
            var chargeItems = [
                new NavItem('systemSetting.chargeField', '收费类型设置', '', 'setting.office&settings.chargeInfo'),
                new NavItem('systemSetting.chargeItem', '收费项目设置', '', 'setting.chargeitemBrowse|dataImport.chargeItem|setting.chargeitemBrowse'),
                new NavItem('systemSetting.chargePayment', '支付方式设置', '', 'setting.chargeitemBrowse'),
            ];
            chargeMenu.addBatch(chargeItems);
            // subItems.push(chargeMenu);

            // 预约中心设置
            subItems.push(new NavItem('systemSetting.appointment', '预约中心设置', '', '(setting.office&settings.rule)|setting.appointment'));

            // 分诊管理设置
            subItems.push(new NavItem('systemSetting.triage', '分诊管理设置', '', 'setting.office|setting.systemsetting'));

            // 患者中心设置
            var patientMenu = new NavItem('', '患者中心设置', '', '^');
            var patientSubItems = [
                new NavItem('systemSetting.patientField', '患者必填项', '', 'setting.office&(settings.newPatientInfo|settings.onlineConsultCreateInfo|settings.checkInInfo)'),
                new NavItem('systemSetting.patientTag', '标签设置', '', 'managementCenter.tagCenter'),
                new NavItem('systemSetting.patientFollowup', '随访设置', '', null),
            ];
            patientMenu.addBatch(patientSubItems);
            subItems.push(patientMenu);

            // 营销中心设置
            var marketingMenu = new NavItem('', '营销中心设置', '', 'membership.categroy|setting.office|membership.point|ReturnVisitFolder.list|patientMgmt.autoRevisitRule|consultCenter.willingParties');
            var marketingItems = [
                new NavItem('systemSetting.marketingReferral', '推荐管理设置', '', 'referralCenter.referralConfig'),
                new NavItem('systemSetting.memberTypes', '会员管理设置', '', 'membership.categroy|setting.office|membership.point'),
                new NavItem('systemSetting.patientRevisit', '回访设置', '', 'patientMgmt.autoRevisitRule'),
                new NavItem('systemSetting.patientConsultant', '咨询设置', '', 'consultCenter.willingParties'),
            ];
            marketingMenu.addBatch(marketingItems);
            // subItems.push(marketingMenu);

            // 库房管理设置
            var supplychainMenu = new NavItem('', '进销存设置', '', 'setting.office&settings.supplychain');

            var supplychainItems = [];
            // 中间节点没有仓库管理，所以没有仓库设置
            var condition = moduleOptionProvider.isNewInventoryOpen() // 新供应链开关
                && ((loginContext.isGroup && loginContext.isRootGroup) // 是rootGroup
                    || !loginContext.isGroup // 不是群组
                    || (loginContext.isGroup // 群组但不是直营
                        && !loginContext.isRegularChain));
            if (condition) {
                supplychainItems.push(new NavItem('systemSetting.supplychainRule', '业务规则设置', '', 'setting.office&settings.supplychain'));
            }

            supplychainItems.push(new NavItem('systemSetting.productBasicDataManagement', '物品信息设置', '', 'product.productInfo'));
            supplychainMenu.addBatch(supplychainItems);
            // subItems.push(supplychainMenu);

            // 诊所中心设置
            var officeManagementMenu = new NavItem('', '诊所中心设置', '', 'schedule.rule|schedule.attendanceConfig|setting.office|setting.approval|settings.checkInInfo|setting.diagnosis|setting.appointment|setting.emrtemplate|dentalLab.product|setting.orthdontic');
            var officeManagementItems = [

                new NavItem('systemSetting.staffManagement', '排班考勤', '', 'schedule.rule|schedule.attendanceConfig'),
                new NavItem('systemSetting.businessManagement.approvalSetting', '审批管理设置', '', 'setting.approval'),
                // new NavItem('new', '支出设置', '', 'setting.office', true, { route: 'systemSetting.office.expend-center' }),
                new NavItem('systemSetting.medicalDiagnosis', '诊断项目', '', 'setting.diagnosis|setting.appointment'),
                new NavItem('systemSetting.medicalRecord', '病历设置', '', 'setting.emrtemplate'),
            ];
            if (moduleOptionProvider.isNewDentalLabEnabled()) {
                // officeManagementItems.push(new NavItem('systemSetting.dentalLab', '技加工设置', '', 'patientOutProcess.config'));
            }
            if (moduleOptionProvider.enableOrthdonticModule()) {
                // officeManagementItems.push(new NavItem('orthdontic.settings', '正畸设置', '', 'setting.orthdontic'));
            }
            officeManagementMenu.addBatch(officeManagementItems);
            subItems.push(officeManagementMenu);

            systemSetting.addBatch(subItems);
            return systemSetting;
        };

        var createPluginMenus = function (appNavItemProvider) {
            if (Ares.plugins) {
                angular.forEach(Ares.plugins, function (plugin) {
                    $log.info('load menu of plugin ' + plugin.name);
                    var menus = plugin.menuInitFn(appNavItemProvider, loginContext);
                    if (angular.isArray(menus)) {
                        angular.forEach(menus, function (menuItem, index) {
                            if (menuItem) {
                                appNavItemProvider.navItems.push(menuItem);
                            }
                        });
                    } else if (menus) {
                        appNavItemProvider.navItems.push(menus);
                    }
                });
            }
        };

        var createOthers = function () {
            //其他项，不在左边导航栏显示
            var others = new NavItem('others', '其他项', '', '', false);
            var subItems = [
                new NavItem('root', 'root'),
                new NavItem('default', 'default'),
                new NavItem('noPermission', 'noPermission'),
                new NavItem('demo', 'demo'),
                new NavItem('AliTurnOn.open', 'aliturnon'),
                new NavItem('systemTool', 'systemTool')
            ];
            others.addBatch(subItems);
            return others;
        };

        var findNavItem = function (id) {
            var theNavItem = null;
            for (var i = 0; i < this.navItems.length; i++) {
                var navItem = this.navItems[i];
                theNavItem = _.find(navItem.subItems, function (subItem) {
                    return subItem.id == id;
                });
                if (theNavItem) {
                    break;
                }
            }
            return theNavItem;
        };

        var initIsShowMallInGroup = function () {
            officeUtil.isRootGroup().then(function (isRoot) {
                if (loginContext.isGroup && !isRoot && loginContext.isRegularChain) {
                    var mallNavItem = _.find(navItems, function (a) {
                        return a.text == '商城';
                    });
                    if (mallNavItem) {
                        mallNavItem.isVisible = false;
                    }
                }
            });
        };

        var initNavItemState = function () {
            var hasActiveItem = false;
            angular.forEach(navItems, function (navItem) {
                var isNavItemActive = false;
                angular.forEach(navItem.allowedSubItems, function (subItem) {
                    if (subItem.id === 'new') {
                        subItem.isActive = $state.includes(subItem.id) && $state.params && $state.params.route &&
                            subItem.param && subItem.param.route && subItem.param.route === $state.params.route;
                    } else {
                        subItem.isActive = $state.includes(subItem.id);
                    }
                    if (subItem.isActive) {
                        navItem.lastVisitedChild = subItem;
                    }
                    // 特殊处理财务中心
                    if ((!subItem.isActive || subItem.text === '财务对账' || subItem.text === '绩效管理') && subItem.subItems) {
                        angular.forEach(subItem.subItems, function (subSubItem) {
                            if (subSubItem.id === 'new') {
                                subSubItem.isActive = $state.includes(subSubItem.id) && $state.params && $state.params.route &&
                                    subSubItem.param && subSubItem.param.route && subSubItem.param.route === $state.params.route;
                            } else {
                                subSubItem.isActive = $state.includes(subSubItem.id);
                            }
                            if (subSubItem.isActive) {
                                navItem.lastVisitedChild = subSubItem;
                            }
                            subItem.isActive |= subSubItem.isActive;
                            if (!subItem.isActive && subSubItem.subItems) {
                                angular.forEach(subSubItem.subItems, function (subSubSubItem) {
                                    subSubSubItem.isActive = $state.includes(subSubSubItem.id);
                                    if (subSubSubItem.id === 'new') {
                                        subSubSubItem.isActive = $state.includes(subSubSubItem.id) && $state.params && $state.params.route &&
                                            subSubSubItem.param && subSubSubItem.param.route && subSubSubItem.param.route === $state.params.route;
                                    } else {
                                        subSubSubItem.isActive = $state.includes(subSubSubItem.id);
                                    }
                                    if (subSubSubItem.isActive) {
                                        navItem.lastVisitedChild = subSubSubItem;
                                    }
                                    subSubItem.isActive |= subSubSubItem.isActive;
                                    subItem.isActive |= subSubItem.isActive;
                                });
                            }
                        });
                    }
                    if (subItem.isActive) {
                        _.each(navItem.allowedSubItems, function (sub) {
                            sub.expanded = false;
                        });
                        subItem.expanded = true;
                    }
                    isNavItemActive |= subItem.isActive;
                });
                if (navItem.id === 'new') {
                    navItem.isActive = isNavItemActive ||
                        (navItem.param.route === 'appointment' && $state.params && $state.params.route && $state.params.route.startsWith('appointment')) ||
                        ($state.params && $state.params.route === navItem.param.route);
                } else {
                    navItem.isActive = isNavItemActive || $state.is(navItem.id);
                }
                if (navItem.id === 'dashBoard') {
                    navItem.isActive = $state.includes(navItem.id);
                }
                hasActiveItem |= navItem.isActive;
            });
            return hasActiveItem;
        };

        var refreshWithPermission = function (navItemProvider) {
            var deferred = $q.defer();
            navItemProvider.navItems = _.filter(navItemProvider.navItems, function (navItem) {
                return navItem && navItem != null;
            });
            permissionProvider.loadPermissions().then(function (permissionCodes) {
                angular.forEach(navItemProvider.navItems, function (navItem) {
                    var allowedSubItems;
                    if (navItem.id === 'others') {
                        allowedSubItems = navItem.subItems;
                    } else {
                        allowedSubItems = _.filter(navItem.subItems, function (subItem) {
                            var allowed = false;
                            if (subItem.permissionCode == '^'
                                && subItem.subItems && subItem.subItems.length > 0) {
                                // 如果子菜单还有子项，任何一个子项有权限，则显示该子菜单。
                                var subSubItems = _.filter(subItem.subItems, function (subSubItem) {
                                    return isNavItemAllowed(subSubItem);
                                });
                                subItem.subItems = subSubItems;
                                allowed = subSubItems && subSubItems.length > 0;
                            } else {
                                subItem.subItems = _.filter(subItem.subItems, function (subSubItem) {
                                    return isNavItemAllowed(subSubItem);
                                });
                                allowed = isNavItemAllowed(subItem);
                            }
                            _.each(subItem.subItems, function (subSubItem) {
                                subSubItem.subItems = _.filter(subSubItem.subItems, function (subSubSubItem) {
                                    return isNavItemAllowed(subSubSubItem);
                                });
                            });
                            return allowed;
                        });
                    }
                    navItem.setAllowedSubItem(allowedSubItems);
                });
                deferred.resolve();
            });
            return deferred.promise;
        };

        var isNavItemAllowed = function (navItem) {
            var allowed = navItem.allowAnoymous || permissionProvider.isAllowed(navItem.permissionCode);
            return allowed;
        };

        var navItems = [];

        (function innerInit(thisObj) {
            thisObj.navItems = navItems;
            thisObj.findNavItem = findNavItem;
            thisObj.initNavItemState = initNavItemState;
        })(this);

        var initializeItems = function (self, officeSetting) {
            self.NavItem = NavItem; // For plugin to create menu.
            if (loginContext.isGroup) {
                var isShow = loginContext.roles.indexOf('网电咨询师') > -1 || loginContext.roles.indexOf('网电主管') > -1;
                if (loginContext.dashboardType === 'WebPhoneConsultant' || isShow) {
                    self.navItems.push(createDashboard());
                }
                else if (loginContext.dashboardType === 'Inventory'
                    && loginContext.isRootGroup
                    && moduleOptionProvider.isGroupInventoryEnabled()) {
                    self.navItems.push(createDashboard());
                }
            } else {
                if (loginContext.dashboardType) {
                    self.navItems.push(createDashboard());
                }
            }
            // 预约中心
            self.appointmentCenter = createScheduleCenter();
            self.navItems.push(self.appointmentCenter);
            // 患者中心
            self.patientHost = createPatientHost();
            self.navItems.push(self.patientHost);
            // 营销中心
            // self.navItems.push(createMarketingManagement());
            // 报表中心
            self.navItems.push(createReportCenter());
            // 进销存
            // self.navItems.push(createSupplychain());
            // 领健商城 根据配置决定是否显示商城
            if (moduleOptionProvider.isMallOpen()) {
                if (permissionProvider.isAllowed('tradingPlatform.list')) {
                    // self.navItems.push(createMallCenter());
                }
            }

            // 根据配置决定是否显示增值服务
            if (moduleOptionProvider.isOpenPlatformEnabled()) {
                // self.navItems.push(createOpenPlatformCenter());
            }

            // 诊所中心
            self.navItems.push(createOfficeManagement(officeSetting));
            // CSSD
            if (moduleOptionProvider.isCssdEnabled()) {
                self.navItems.push(createCssd());
            }
            // 技加工
            // self.navItems.push(createDentalManagement());

            // 系统设置
            self.navItems.push(createSystemSetting());

            self.navItems.push(createOthers());

            createPluginMenus(self);
            if (loginContext.isGroup) {
                initIsShowMallInGroup(self);
            }
            return refreshWithPermission(self);
        };

        var fillReportSet = function (navItems, setState, setName) {
            var reportSet = _(reportSetConfigs).find(function (c) {
                return c.name === setName;
            });
            if (reportSet && reportSet.reports && reportSet.reports.length > 0) {
                var setPermission = null;
                if (_(reportSet.reports).every(function (r) { return r.permissionCode; })) {
                    setPermission = _(reportSet.reports).pluck('permissionCode').join('|');
                }
                navItems.push(new NavItem(setState, reportSet.displayName, '', setPermission));
            }
        };

        this.initialize = function () {
            var deferred = $q.defer();
            var self = this;
            if (!dataDicSvc.reportSetConfigDic) {
                dataDicSvc.initialize();
            }
            $q.all([
                officeOptionSvc.getOfficeOption(officeOptionSvc.optionKeys.IsMedicalExamOpen),
                dataDicSvc.reportSetConfigDic.load(),
                systemConfigSvc.getIsLcCrmEnabled(),
                officeOptionSvc.getOfficeOption(officeOptionSvc.optionKeys.PaymentTypeUpgradeStatus),
            ]).then(function (data) {
                isMedicalExamOpen = data[0];
                reportSetConfigs = data[1];
                isLcCrmEnabled = data[2];
                var upgradeStatus = parseInt(data[3]);
                isPaymentTypeUpgradeFinished = upgradeStatus === enums.PaymentTypeUpgradeStatus.Finished;
                isPaymentTypeUpgradeInitialized = upgradeStatus === enums.PaymentTypeUpgradeStatus.InitUpgraded;
                dataDicSvc.officeSettingDic.load().then(function (officeSetting) {
                    initializeItems(self, officeSetting).then(function () {
                        deferred.resolve();
                    });
                });
            });
            return deferred.promise;
        };
    }]);

/**
 * 把hebe页面简单地包一层，用作tab下的ui-view
 */
var framework;
(function (framework) {
    'use strict';
    var Ares3PageContainerView = /** @class */ (function () {
        function Ares3PageContainerView() {
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-container\">\n                <style>\n                    .ares3-page-container {\n                        padding: 8px;\n                        background: #fff;\n                    }\n                </style>\n                <div ui-view></div>\n            </div>\n        ";
        }
        Ares3PageContainerView.$inject = [];
        return Ares3PageContainerView;
    }());
    frameworkModule.directive('ares3PageContainerView', Ares.tsDirective(Ares3PageContainerView));
})(framework || (framework = {}));

ares3Module.controller('Ares3SideBarController',
['$scope', '$log', '$timeout', '$rootScope', 'ares3NavItemProvider', 'appNav', 'officeSvc', 'localSvc',
    '$stateParams', 'hebePortal', 'permissionProvider',
function ($scope, $log, $timeout, $rootScope, ares3NavItemProvider, appNav, officeSvc, localSvc,
          $stateParams, hebePortal, permissionProvider) {

    'use strict';

    var navigate = function (subItem) {
        console.log("SSSSSSS");
        // 有tab的三级菜单
        if (!subItem.id && subItem.subItems) {
            var firstAvailableItem = _.find(subItem.subItems, function (item) {
                return permissionProvider.isAllowed(item.permissionCode);
            });
            appNav.goToState(firstAvailableItem.id, firstAvailableItem.param);
            return;
        }
        // 特殊处理增值服务
        if (subItem.id === 'new' && subItem.param.route === 'enterpriseCenter.services') {
            console.log("增值服务入口");
            Ares.sensors.track('ClinicCenter', {
                'OperationType': '增值服务入口',
            });
        }
        if (!subItem.isActive || (subItem.id === 'new' && $stateParams.route !== subItem.param.route)) {
            // console.log("进来了");
            console.log(subItem.param);
            if(subItem.param && subItem.param.route == "appointment"){
                subItem.param.route = "appointment.scheduler";
            }
            appNav.goToState(subItem.id, subItem.param);
        }
    };

    // 二级菜单点击
    var onSubItemClick = function (subItem) {
        // 如有三级，则切换展开
        if (subItem.subItems && subItem.subItems.length > 0) {
            subItem.expanded = !subItem.expanded;
            $timeout(function () {
                $scope.updateSubMenuScroll();
                $scope.updateSubMenuPopScroll();
            }, 0, false);
            return;
        }
        navigate(subItem);
    };

    var getPoint = function () {
        officeSvc.getOfficePoint().then(function (result) {
            $scope.officePoint = result.data;
        })
    };

    (function initialize() {
        $scope.navItems = ares3NavItemProvider.navItems;
        $scope.navigate = navigate;
        $scope.onSubItemClick = onSubItemClick;
        getPoint();
        $rootScope.$on('officePointChange', function (event, bool) {
            if (bool) {
                getPoint();
            }
        });
    }());
}
]);

ares3Module.directive('ares3SideBar',
['$log', '$timeout', 'eventAggregator', '$rootScope', 'officeUtil', 'loginContext', '$stateParams', 'hebePortal', '$state',
function ($log, $timeout, eventAggregator, $rootScope, officeUtil, loginContext, $stateParams, hebePortal, $state) {
    'use strict';

    return {
        restrict: 'E',
        templateUrl: '/app-ares3/framework/ares3-side-bar/ares3-side-bar.html',
        replace: true,
        scope: {},
        controller: 'Ares3SideBarController',

        link: function ($scope, element, attrs) {
            var subMenuPopover = element.find('.sidebar-sub-pop');
            var subMenu = element.find('.sidebar-sub');

            var initView = function () {
                // Add class everytime a mouse pointer hover over it
                var hoverTimeout;
                $('.nav-sidebar > li').hover(function () {
                    clearTimeout(hoverTimeout);
                    $(this).siblings().removeClass('nav-hover');
                    $(this).addClass('nav-hover');
                }, function () {
                    var $self = $(this);
                    hoverTimeout = setTimeout(function () {
                        $self.removeClass('nav-hover');
                    }, 200);
                });
                $('.nav-sidebar > li .children').hover(function () {
                    clearTimeout(hoverTimeout);
                    $(this).closest('.nav-parent').siblings().removeClass('nav-hover');
                    $(this).closest('.nav-parent').addClass('nav-hover');
                }, function () {
                    var $self = $(this);
                    hoverTimeout = setTimeout(function () {
                        $(this).closest('.nav-parent').removeClass('nav-hover');
                    }, 200);
                });

                createSideScroll();
                $timeout(function () {
                    updateSubMenuScroll();
                }, 0, false);
            };

            var refreshView = function (navItem) {
                console.log(navItem);
                if (!navItem.hasVisibleSubItem) {
                    $scope.navigate(navItem);
                } else {
                    if (navItem.lastVisitedChild) {
                        $scope.navigate(navItem.lastVisitedChild);
                    } else {
                        $scope.navigate(navItem.allowedSubItems[0]);
                    }
                    $timeout(function () {
                        updateSubMenuScroll();
                    }, 0, false);

                }

            };

            var onAppInitialized = function () {
                $timeout(initView, 200);
            };

            var checkInventoryNewBadge = function () {
                var showInventoryNew = localStorage.getItem('newInventoryHome_showGuide');
                $scope.showInventoryNewBadge = showInventoryNew !== 'never';
            };

            var checkMallCenterVisible = function () {
                if (!loginContext.isRootGroup) {
                    officeUtil.getGroupProcurementMethod().then(function (value) {
                        if (value === 'group') {
                            element.find('.nav-sidebar-item-mallcenter').parent().remove();
                        }
                    })
                }
            };

            var checkActive = function(subItem, navItem) {
                if (subItem.id === 'new') {
                    var isActive =  $stateParams.route === subItem.param.route;
                    if (isActive) {
                        navItem.isActive = true
                    }
                    return isActive
                } else {
                    return subItem.isActive || $state.current.name === subItem.id;
                }
            };

            var listenRouteSyncFromHebel = function () {
                hebePortal.register('ares.router.syncRoute', function () {
                    $scope.$apply();
                })
            };

            var onMainMenuMouseOver = function (menuItem) {
                if (menuItem.delayedHoveringMenuChange) {
                    $timeout.cancel(menuItem.delayedHoveringMenuChange);
                }
                menuItem.delayedHoveringMenuChange = $timeout(function () {
                    menuItem.isHovering = true;
                    if (menuItem.allowedSubItems && menuItem.allowedSubItems.length > 0) {
                        $scope.isPopMenuVisible = true;
                    }
                }, 100);
                // if (menuItem.allowedSubItems && menuItem.allowedSubItems.length > 0 && _.some(menuItem.allowedSubItems, function (item) {
                //     return item.isVisible
                // })) {
                //     if (subMenuPopover.is(':visible')) {
                //         subMenuPopover.find('>div, >ul').css('opacity', 0);
                //         delayedHoveringMenuChange = $timeout(function () {
                //             $scope.hoveringMainMenu = menuItem;
                //             subMenuPopover.find('>div, >ul').css('opacity', 1);
                //         }, 100);
                //     } else {
                //         $scope.hoveringMainMenu = menuItem;
                //     }
                //
                //     // if (delayedSubMenuPopoverHide) {
                //     //     $timeout.cancel(delayedSubMenuPopoverHide);
                //     // }
                //     $timeout(function () {
                //         updateSubMenuPopScroll();
                //     }, 0, false);
                //     subMenuPopover.fadeIn();
                // } else {
                //     onMainMenuMouseLeave();
                // }
                // menuItem.isHovering = true;
            };

            var delayedSubMenuPopoverHide;
            var onMainMenuMouseLeave = function (menuItem) {
                if (menuItem.delayedHoveringMenuChange) {
                    $timeout.cancel(menuItem.delayedHoveringMenuChange);
                }
                menuItem.delayedHoveringMenuChange = $timeout(function () {
                    menuItem.isHovering = false;
                    $scope.isPopMenuVisible = false;
                }, 100);
                // if (delayedSubMenuPopoverHide) {
                //     $timeout.cancel(delayedSubMenuPopoverHide);
                // }
                // delayedSubMenuPopoverHide = $timeout(function () {
                //     subMenuPopover.fadeOut();
                //     $scope.hoveringMainMenu = null;
                // }, 100);
            };

            var onSubMenuMouseOver = function (menuItem) {
                if (menuItem.delayedHoveringMenuChange) {
                    $timeout.cancel(menuItem.delayedHoveringMenuChange);
                }
            };

            var onSubMenuMouseLeave = function (menuItem) {
                // subMenuPopover.hide();
                // $scope.hoveringMainMenu = null;
                menuItem.isHovering = false;
                $scope.isPopMenuVisible = false;
            };

            var checkMainMenuActive = function (menuItem) {
                if (menuItem.id === 'new' && menuItem.param && menuItem.param.route === 'appointment' &&
                    $stateParams.route && $stateParams.route.startsWith('appointment')) {
                    menuItem.isActive =  true;
                }
                // 特殊处理诊所概览
                if ($stateParams.route && $stateParams.route === 'enterpriseCenter.overview') {
                    menuItem.isActive =  false;
                    $scope.currentMainMenu = null;
                }
                if (menuItem.isActive) {
                    $scope.currentMainMenu = menuItem;
                }
                return menuItem.isActive;
            };

            var toggleSubMenuVisible = function (visible) {
                $scope.subMenuVisible = visible;
                if (visible) {
                    angular.element('body').addClass('submenu-visible');
                } else {
                    angular.element('body').removeClass('submenu-visible');
                }
                eventAggregator.publish(eventAggregator.events.sidebarSubMenuToggle, {subMenuVisible: visible});
            };

            var updateSubMenuScroll = function () {
                if (subMenu.data('mCustomScrollbarIndex')) {
                    subMenu.mCustomScrollbar('update')
                } else {
                    subMenu.mCustomScrollbar({
                        scrollButtons: {
                            enable: false
                        },
                        autoHideScrollbar: true,
                        scrollInertia: 300,
                        advanced: {
                            updateOnContentResize: true
                        }
                    })
                }
            };

            var updateSubMenuPopScroll = function () {
                if (subMenuPopover.data('mCustomScrollbarIndex')) {
                    subMenuPopover.mCustomScrollbar('update')
                } else {
                    subMenuPopover.mCustomScrollbar({
                        scrollButtons: {
                            enable: false
                        },
                        autoHideScrollbar: true,
                        scrollInertia: 300,
                        advanced: {
                            updateOnContentResize: true
                        }
                    })
                }
            };

            (function initialize() {
                $scope.subMenuVisible = true;
                checkInventoryNewBadge();
                listenRouteSyncFromHebel();
                $scope.refreshView = refreshView;
                $scope.checkActive = checkActive;
                $scope.onMainMenuMouseOver = onMainMenuMouseOver;
                $scope.onMainMenuMouseLeave = onMainMenuMouseLeave;
                $scope.onSubMenuMouseOver = onSubMenuMouseOver;
                $scope.onSubMenuMouseLeave = onSubMenuMouseLeave;
                $scope.checkMainMenuActive = checkMainMenuActive;
                $scope.toggleSubMenuVisible = toggleSubMenuVisible;
                $scope.updateSubMenuScroll = updateSubMenuScroll;
                $scope.updateSubMenuPopScroll = updateSubMenuPopScroll;
                $scope.currentMainMenu = null;
                $scope.hoveringMainMenu = null;
                $scope.isPopMenuVisible = false;
                if ($rootScope.isInitialized) {
                    $timeout(initView, 200);
                } else {
                    eventAggregator.subscribe($scope, 'appInitialized', onAppInitialized);
                }
                eventAggregator.subscribe($scope, 'InventoryNewGuideHideForever', checkInventoryNewBadge);
                eventAggregator.subscribe($scope, 'appInitialized', checkMallCenterVisible);
                eventAggregator.subscribe($scope, eventAggregator.events.HideSidebarSubMenu, function () {
                    toggleSubMenuVisible(false);
                    $('#ares3-top-bar').css({'left': '80px'});
                    if ($scope.currentMainMenu && $scope.currentMainMenu.hasVisibleSubItem) {
                        angular.element('.sidebar-sub-label-show').tooltip('show');
                    }
                });
                $scope.$watch('currentMainMenu', function (val) {
                    if (val && val.hasVisibleSubItem && $scope.subMenuVisible) {
                        angular.element('body').addClass('submenu-visible');
                        $timeout(function () {
                            updateSubMenuScroll();
                        }, 0, false);
                        $('#ares3-top-bar').css({'left': '200px'});
                    } else {
                        angular.element('body').removeClass('submenu-visible');
                        $('#ares3-top-bar').css({'left': '80px'});
                    }
                });
            }());
        }
    }
}]);

ares3Module.controller('Ares3SideBarSearchController',

['$scope', '$rootScope', '$q', '$injector', 'loginContext', 'permissionProvider', 'officeUtil', 'officeOptionSvc', 'moduleOptionProvider',
    'dataDicSvc', 'systemConfigSvc', 'systemConfigUtil', 'chargeSvc',
function($scope, $rootScope, $q, $injector, loginContext, permissionProvider, officeUtil, officeOptionSvc, moduleOptionProvider,
    dataDicSvc, systemConfigSvc, systemConfigUtil, chargeSvc) {
    'use strict';

    // 高级报表配置
    var reportSetConfigs;
    // 是否启用领健CRM
    var isLcCrmEnabled;
    /**
     * 菜单列表
     * @type {Array}
     * 数据结构：
     *      {
     *          text: string;           // 菜单名称
     *          state: string;          // 菜单路由
     *          permissionCode: string; // 菜单权限
     *          navItemName: string;    // 传入菜单名称，用于新旧版本时可以根据当前值，判断是否允许搜索当前菜单下的子级菜单名称
     *          param: object;          // 其他参数
     *              {
     *                  route: string;  // 3.0 路由
     *              }
     *
     *      }
     */
    var menuSearchList = [];

    var navItemProvider = window.Ares3
        ? $injector.get('ares3NavItemProvider')
        : $injector.get('appNavItemProvider');

    /**
     * 搜索过滤菜单项
     */
    var filterMenus = function (searchText) {
        return false;
        if (!searchText) {
            $scope.menus = [];
            return;
        }
        $scope.menus = _.filter(menuSearchList, function (d) {
            var isVisible = true;
            // 如果没有传入 navItemName ，则默认显示
            if (d.navItemName) {
                isVisible = navItemProvider.findNavItem(d.navItemName) && navItemProvider.findNavItem(d.navItemName).isVisible;
            }
            var isAllowed = permissionProvider.isAllowed(d.permissionCode);
            var isMatch = d.text.toLocaleLowerCase().indexOf(searchText.toLocaleLowerCase().trim()) > -1;
            return isVisible && isAllowed && isMatch;
        });

        _.forEach($scope.menus, function (item) {
            item.html = getMatchText(item.text);
        });
    };

    /**
     * 获取匹配到的值
     */
    var getMatchText = function (str) {
        if (!str || !$scope.searchText || str.indexOf($scope.searchText) === -1) return str;
        var reg = new RegExp('(' + $scope.searchText + ')', 'ig');
        return str.replace(reg, '<span>$1</span>');
    };

    var createDashboard = function () {
        if (loginContext.dashboardType === 'Inventory') {
            return [{ text: '我的工作', state: 'new', permissionCode: null, param: { route: 'supplychain.dashboard' } }];
        }
        return [{ text: '我的工作', state: 'dashBoard', permissionCode: null }];
    };

    // 患者中心
    var createPatientHost = function () {
        return [
            {
                text: '所有患者',
                state: 'patientRelationship.patientAdvanceSearch',
                permissionCode: 'patientMgmt.browse|patientMgmt.heathInsurance|patientMembership.browse|patientCharge.history|patientMgmt.apptRecord|patientMgmt.diagnoseRecord|patientMgmt.txplan|patientMgmt.consultRecord|patientMgmt.orthdontic|patientMgmt.revisitRecord|patientImaging.list|patientDocument.list|generalExam.history|perioExam.history|patientFollowup.history|patientOutProcess.history|patientPrescription.history|patientLisOrder.history|patientMedicalRecord.list|dataImport.patient',
            },
            { text: '重复患者', state: 'newPatientManagement.duplicate.list', permissionCode: 'patientCenter.duplicatedPatient' },
            // { text: '归档患者', state: 'newPatientManagement.archived.list', permissionCode: 'patientCenter.archivedPatient' },
            { text: '患者导入', state: 'newPatientManagement.import.list', permissionCode: 'dataImport.patient' },
            { text: '随访记录', state: 'newPatientManagement.followup.list', permissionCode: 'followup.list' },
            { text: '最近随访', state: 'newPatientManagement.followup.last', permissionCode: 'followup.last' },
            { text: '投诉管理', state: 'complaint.list', permissionCode: 'complaintManagement.list' },
            // { text: '预检分诊', state: 'pttCenter', permissionCode: 'precheckTriage.view' }
        ];
    };

    // 预约中心
    var createScheduleCenter = function () {
        if (loginContext.isGroup) {
            return [
                { text: '预约视图', state: 'newGroupScheduleCenter.groupCalendar', permissionCode: 'scheduleCenter.calendar' },
                { text: '预约查询', state: 'newGroupScheduleCenter.apptList', permissionCode: 'scheduleCenter.calendar' },
                { text: '网络预约', state: 'newGroupScheduleCenter.applyList', permissionCode: 'scheduleCenter.calendar' }
            ];
        }
        return [
            { text: '预约看板', state: 'new', permissionCode: 'scheduleCenter.calendar', param: { route: 'appointment.scheduler' } },
            { text: '预约列表', state: 'new', permissionCode: 'scheduleCenter.search', param: { route: 'appointment.list' } },
            { text: '网络预约', state: 'new', permissionCode: 'scheduleCenter.weixinApplyList', param: { route: 'appointment.apply' } }
        ];
    };

    // 进销存/供应链
    var createSupplychain = function () {
        $q.all([
            officeUtil.getGroupProcurementMethod(),
            officeUtil.checkSelfSettlementEnabled(),
        ]).then(function (values) {
            var groupProcurementEnabled = values[0] !== 'self';
            var selfSettlementEnabled = values[1];
            var states = [];

            /**
             * 基础信息
             */
            var productMgmt = [];
            if (values[0] === 'group' && !loginContext.isGroup) {
                productMgmt.push({ text: '物品管理', state: 'supplychain.product.list', permissionCode: 'product.productInfo' });
            } else {
                productMgmt.push(
                    { text: '物品管理', state: 'supplychain.product.list', permissionCode: 'product.productInfo' },
                    { text: '供应商管理', state: 'supplychain.product.supplier', permissionCode: 'product.supplierInfo' }
                );
            }
            // 中间节点没有仓库管理，所以没有长裤设置
            var condition = loginContext.isGroup && !moduleOptionProvider.isGroupInventoryEnabled();
            if (!condition) {
                productMgmt.push({ text: '仓库设置', state: 'supplychain.product.warehouse', permissionCode: 'warehouse.warehouseManagement' });
            }


            /**
             * 耗材追溯
             */
            var traceabilityMgmt = [{ text: '耗材追溯', state: 'supplychain.traceability', permissionCode: 'warehouse.warehouseManagement' }];

            /**
             * 仓库管理
             */
            var inventoryMgmt = [
                { text: '库存管理', state: 'supplychain.inventory.manage', permissionCode: 'inventoryBrowse.stockStatus' },
                { text: '库存流水', state: 'supplychain.inventory.flow', permissionCode: 'inventoryBrowse.stockCountSummary' },
                { text: '入库管理', state: 'supplychain.inventory.inorder', permissionCode: 'inventoryOperation.stockInBrowser' },
                { text: '出库管理', state: 'supplychain.inventory.outorder', permissionCode: 'inventoryOperation.stockOutBrowser' },
                { text: '调拨管理', state: 'supplychain.inventory.transfer', permissionCode: 'inventoryOperation.stockTransferBrowser' },
                { text: '盘点管理', state: 'supplychain.inventory.check', permissionCode: 'inventoryOperation.stockCheck' }
            ];


            /**
             * 采购管理
             */
            var procurementMgmt = [];
            //当前诊所是否群组节点
            if (loginContext.isGroup) {
                //当前诊所是否开启库存管理
                if (moduleOptionProvider.isGroupInventoryEnabled()) {
                    //当前诊所是根节点且开启总部集采
                    if (loginContext.isRootGroup && groupProcurementEnabled) {
                        procurementMgmt.push({ text: '诊所采购申请', state: 'supplychain.procurement.groupApply', permissionCode: 'procurement.procurementManageOfficeApply' });
                    }
                    procurementMgmt.push(
                        { text: '采购助手', state: 'supplychain.procurement.assistance', permissionCode: 'procurement.procurementViewAssistant' },
                        { text: '采购单', state: 'supplychain.procurement.order', permissionCode: 'procurement.procurementViewPayOrder' },
                        { text: '采购退货单', state: 'supplychain.procurement.returnOrder', permissionCode: 'procurement.procurementViewPayOrder' }
                    );
                } else {
                    //当前诊所是根节点且开启总部集采
                    if (loginContext.isRootGroup && groupProcurementEnabled) {
                        procurementMgmt.push({ text: '诊所采购申请', state: 'supplychain.procurement.groupApply', permissionCode: 'procurement.procurementManageOfficeApply' });
                    }
                    procurementMgmt.push({ text: '采购单', state: 'supplychain.procurement.order', permissionCode: 'procurement.procurementViewPayOrder' });
                }
                //当前诊所是根节点
                if (loginContext.isRootGroup) {
                    procurementMgmt.push({ text: '供应商结算', state: 'supplychain.procurement.settlementOrder', permissionCode: 'procurement.supplierSettlement' });
                }
            } else {
                procurementMgmt.push({ text: '采购助手', state: 'supplychain.procurement.assistance', permissionCode: 'procurement.procurementViewAssistant' });
                if (groupProcurementEnabled) {
                    procurementMgmt.push({ text: '采购申请', state: 'supplychain.procurement.apply', permissionCode: 'procurement.procurementManageOfficeApply' });
                }
                procurementMgmt.push(
                    { text: '采购单', state: 'supplychain.procurement.order', permissionCode: 'procurement.procurementViewPayOrder' },
                    { text: '采购退货单', state: 'supplychain.procurement.returnOrder', permissionCode: 'procurement.procurementViewPayOrder' }
                );
                if (selfSettlementEnabled) {
                    procurementMgmt.push({ text: '供应商结算', state: 'supplychain.procurement.settlementOrder', permissionCode: 'procurement.supplierSettlement' });
                }
            }

            if (isNeedCheckAgreePrice && (loginContext.isRootGroup || !loginContext.isRegularChain)) {
                // procurementMgmt.push({ text: '商城报价管理', state: 'supplychain.procurement.quotationProduct', permissionCode: 'procurement.mallQuotationManagement' });
            }


            /**
             * 进销存报表
             */
            var supplychainReportMgmt = [
                // { text: '进销存汇总表', state: 'supplychainReport.inventorySummary', permissionCode: 'supplychainReport.inventorySummary' }
            ];
            var isBigDataEnabled = moduleOptionProvider.isBigDataEnabled();
            var isTenantBigDataEnabled = moduleOptionProvider.isTenantBigDataEnabled();
            if (isBigDataEnabled || isTenantBigDataEnabled) {
                // supplychainReportMgmt.push({ text: '概览(进销存报表)', state: 'supplychainReport.dashboard', permissionCode: 'supplychainReport.overview' });
            }
            if (isBigDataEnabled || isTenantBigDataEnabled) {
                supplychainReportMgmt.push(
                    // { text: '采购报表', state: 'supplychainReport.purchaseSummary', permissionCode: 'supplychainReport.purchaseSummary' },
                    // { text: '领用报表', state: 'supplychainReport.takeSummary', permissionCode: 'supplychainReport.takeSummary' }
                );
            }
            if (selfSettlementEnabled) {
                // supplychainReportMgmt.push({ text: '供应商对账及付款流水', state: 'supplychainReport.supplierSettlementHistory', permissionCode: 'supplychainReport.supplierSettlementHistory' });
            }
            if (isBigDataEnabled || isTenantBigDataEnabled) {
                // supplychainReportMgmt.push({ text: '销售报表', state: 'supplychainReport.salesSummary', permissionCode: 'supplychainReport.salesSummary' });
            }


            // 当前诊所是否群组节点
            if (loginContext.isGroup) {
                // 当前诊所是否开启库存管理
                if (moduleOptionProvider.isGroupInventoryEnabled()) {
                    states = states.concat(inventoryMgmt, traceabilityMgmt);
                }
                // 当前诊所是根节点
                if (loginContext.isRootGroup) {
                    if (moduleOptionProvider.isInventoryTakeWorkflowEnabled()) {
                        states.push({ text: '领用申请单', state: 'supplychain.myApply.takeOrderList', permissionCode: 'Application.fillApplication' });
                    }
                }
            } else {
                if (moduleOptionProvider.isInventoryTakeWorkflowEnabled()) {
                    states.push({ text: '领用申请单', state: 'supplychain.myApply.takeOrderList', permissionCode: 'Application.fillApplication' });
                }
                states = states.concat(inventoryMgmt, traceabilityMgmt);
            }

            //物品管理排最后
            states = states.concat(procurementMgmt, productMgmt, supplychainReportMgmt);

            menuSearchList = menuSearchList.concat(states);
        });
    };

    // 报表中心
    var createReportCenter = function () {
        var states = [];

        // 运营分析 - 患者分析
        var operationItems = [
            { text: '患者分析', state: 'reportCenter.patient.summary', permissionCode: 'operation.patienttAnalysis' },
            { text: '新增患者', state: 'reportCenter.patient.newPatient', permissionCode: 'tenantReport.newPatients' },
            { text: '推荐人分析', state: 'reportCenter.patient.referrer', permissionCode: 'operation.referrer' },
            { text: '患者来源分析', state: 'reportCenter.patient.source', permissionCode: 'operation.patientSource' }
        ];
        if (isNewPaymentTypeEnabled) {
            operationItems.push({ text: '患者消费统计', state: 'reportCenter.patient.consumption', permissionCode: 'finance.patientConsumption' });
        }

        // 运营分析 - 预约分析
        var apptItems = [
            { text: '预约分析', state: 'reportCenter.appointment.summary', permissionCode: 'operation.apptAnalysis' },
            { text: '预约趋势', state: 'reportCenter.appointment.trend', permissionCode: 'tenantReport.apptTrend' }
        ];
        fillReportSet(apptItems, 'reportCenter.appointment.attendance', 'PatientAppointmentAnalysisReportSet');

        // 运营分析 - 营销分析
        // states.push({ text: '卡券管理', state: 'reportCenter.marketing.gift', permissionCode: 'operation.gift' });

        // 运营分析 - 营收分析
        states.push(
            // { text: '营收分析', state: 'reportCenter.revenue.summary', permissionCode: 'operation.amounttAnalysis' },
            // { text: '收入统计', state: 'reportCenter.revenue.incomeSummary', permissionCode: 'tenantReport.incomeSummary' },
            // { text: '收入趋势', state: 'reportCenter.revenue.incomeTrend', permissionCode: 'tenantReport.incomeTrend' }
        );

        // 运营分析 - 运营分析统计
        states.push({ text: '运营分析统计', state: 'reportCenter.operation.analysis', permissionCode: 'operation.analysis' });

        // 绩效中心 - 个人绩效
        if (!loginContext.isTenantAdmin && loginContext.dashboardRoleType !== '财务') {
            var personalperformanceState = [
                // { text: '收费明细', state: 'personalperformance.chargeDetailView', permissionCode: null },
                // { text: '账单明细（收入明细）', state: 'personalperformance.chargeDetail', permissionCode: null },
                // { text: '收费大类', state: 'personalperformance.chargeCategoryView', permissionCode: null }
            ];

            if (!loginContext.isGroup && loginContext.providerJob !== "护士") {
                personalperformanceState.push({ text: '就诊人次', state: 'personalperformance.doctorApptView', permissionCode: null })
            }
            if (loginContext.providerJob === "咨询师") {
                personalperformanceState = [{ text: '工作汇总', state: 'personalperformance.consultantView', permissionCode: null }];
            }
            if (loginContext.providerJob === "牙医助理") {
                personalperformanceState = [{ text: '工作汇总', state: 'personalperformance.assistantView', permissionCode: null }];
            }
            if (loginContext.providerJob === "网电营销") {
                personalperformanceState = [{ text: '工作汇总', state: 'personalperformance.networkConsultantView', permissionCode: null }];
            }
            if (loginContext.providerJob === "前台") {
                personalperformanceState = [{ text: '账单明细（收入明细）', state: 'personalperformance.chargeDetail', permissionCode: null }];
            }
            states = states.concat(personalperformanceState);
        }

        // 根据配置决定是否显示定制报表
        if (moduleOptionProvider.isCustomMadeReportOpen()) {
            states.push({ text: '定制报表', state: 'reportCenter.custom', permissionCode: 'customerMadeFolder.otherReport' });
        }

        // 我的报表
        var mineReport = [{ text: '报表下载', state: 'reportCenter.mine.offline', permissionCode: 'finance.myReport' }];
        if (loginContext.providerJob === '咨询师') {
            mineReport.push(
                { text: '账单明细', state: 'reportCenter.mine.chargeDetail', permissionCode: 'myReport.all' },
                { text: '项目明细', state: 'reportCenter.mine.chargeItemDetail', permissionCode: 'myReport.all' },
                { text: '欠费患者', state: 'reportCenter.mine.overduePatient', permissionCode: 'myReport.all' },
                { text: '储值卡余额', state: 'reportCenter.mine.membershipBalance', permissionCode: 'myReport.all' },
                { text: '储值卡余额变动记录', state: 'reportCenter.mine.membershipSummary', permissionCode: 'myReport.all' },
                { text: '咨询师工作汇总', state: 'reportCenter.mine.consultantReport', permissionCode: 'myReport.all' }
            );
        }

        states = states.concat(
            operationItems,
            apptItems,
            // _performanceReportOfNewOrOld(),
            // _financeReportOfNewOrOld(),
            mineReport
        );
        return states;
    };

    // 新版/旧版报表：绩效中心
    var _performanceReportOfNewOrOld = function () {
        var newPerformanceItems = [];
        var oldPerformanceItems = [];

        /**
         * 新版
         */
        if (reportSetConfigs) {
            switch (loginContext.providerJob) {
                case "医生":
                    fillReportSet(newPerformanceItems, 'performancev2.personalDoctorPerformanceSetV3', 'PersonalDoctorPerformanceSet', 'performancev2');
                    break;
                case "护士":
                    fillReportSet(newPerformanceItems, 'performancev2.personalNursePerformanceSetV3', 'PersonalNursePerformanceSet', 'performancev2');
                    break;
                case "咨询师":
                    fillReportSet(newPerformanceItems, 'performancev2.personalConsultPerformanceSetV3', 'PersonalConsultPerformanceSet', 'performancev2');
                    break;
                default:
                    break;
            }
            fillReportSet(newPerformanceItems, 'performancev2.onlineConsultPerformanceSet', 'DashboardOnlineConsultPerformanceSet', 'performancev2');
            fillReportSet(newPerformanceItems, 'performancev2.doctorPerformanceSet', 'DoctorPerformanceSet', 'performancev2');
            fillReportSet(newPerformanceItems, 'performancev2.consultPerformanceSet', 'ConsultPerformanceSet', 'performancev2');
            fillReportSet(newPerformanceItems, 'performancev2.nursePerformanceSet', 'NursePerformanceSet', 'performancev2');
            fillReportSet(newPerformanceItems, 'performancev2.statementSearchSet', 'StatementSearchSet', 'performancev2');
            if (isMedicalExamOpen) {
                newPerformanceItems.push({ text: '拍片绩效', state: 'reportCenter.performance.medicalExam', permissionCode: 'performancev2.medicalExam', navItemName: 'performancev2' });
            }
        }


        /**
         * 旧版
         */
        oldPerformanceItems = [
            { text: '医生收费明细', state: 'performance.chargeDetailView', permissionCode: 'performance.doctorChargeDetail', navItemName: 'performance' },
            { text: '医生就诊人次', state: 'performance.doctorApptView', permissionCode: 'performance.doctorVisits', navItemName: 'performance' },
            { text: '护士收费明细', state: 'performance.nurseChargeDetailView', permissionCode: 'performance.nurseChargeDetail', navItemName: 'performance' },
            { text: '护士收费大类', state: 'performance.nurseChargeCategoryView', permissionCode: 'performance.nurseChargeCategroy', navItemName: 'performance' },
            { text: '牙医助理工作汇总', state: 'performance.assistantReport', permissionCode: 'performance.assistantWorkSummary', navItemName: 'performance' },
            { text: '预约绩效查询', state: 'performance.apptPerformanceView', permissionCode: 'performance.doctorApptPerformance', navItemName: 'performance' },
            { text: '转诊工作量', state: 'performance.apptTransferredView', permissionCode: 'performance.apptTransferred', navItemName: 'performance' },
            { text: '执行划扣', state: 'performance.chargeDeductionView', permissionCode: 'performance.chargeDeduction', navItemName: 'performance' },
            { text: '网电绩效', state: 'performance.networkConsult', permissionCode: 'performance.networkConsult', navItemName: 'performance' },
            { text: '咨询师绩效', state: 'performance.consultPerformanceView', permissionCode: 'performance.consultPerformanceView', navItemName: 'performance' }
        ];

        if (loginContext.isGroup) {
            oldPerformanceItems.splice(1, 0, { text: '医生收费大类', state: 'performance.groupChargeCategoryView', permissionCode: 'performance.doctorChargeCategroy', navItemName: 'performance' });
        } else {
            oldPerformanceItems.splice(1, 0, { text: '医生收费大类', state: 'performance.chargeCategoryView', permissionCode: 'performance.doctorChargeCategroy', navItemName: 'performance' });
        }
        if (moduleOptionProvider.isDelunCustomFeatureOpen()) {
            oldPerformanceItems.push({ text: '确认应收', state: 'performance.chargePlanpriceConfirmedView', permissionCode: 'performance.chargeDeduction', navItemName: 'performance' });
        }

        if (isMedicalExamOpen) {
            oldPerformanceItems.push({ text: '拍片绩效', state: 'performance.medicalExamView', permissionCode: 'performance.medicalExam', navItemName: 'performance' });
        }

        if (enableConsultantDiagnose) {
            oldPerformanceItems.splice(5, 0, { text: '咨询师收费大类', state: 'performance.consultantChargeCategoryView', permissionCode: 'performance.consultantChargeCategory', navItemName: 'performance' });
            oldPerformanceItems.splice(6, 0, { text: '咨询师工作汇总', state: 'performance.consultantReport', permissionCode: 'performance.consultantWorkSummary', navItemName: 'performance' });
        }

        return [].concat(newPerformanceItems, oldPerformanceItems);
    };

    // 新版/旧版报表：财务中心
    var _financeReportOfNewOrOld = function () {
        // 财务报表/财务中心
        var newFinanceReportItems = [];
        var oldFinanceReportItems = [];

        /**
         * 新版
         */
        if (!loginContext.isGroup) {
            newFinanceReportItems.push({ text: '对账日历', state: 'reportCenter.financeCalendar', permissionCode: 'financev2.checkCalendar', navItemName: 'financev2' });
        }
        if (reportSetConfigs) {
            fillReportSet(newFinanceReportItems, 'financev2.dailyCheckReportCashflowSet', 'DailyCheckReportCashflowSet', 'financev2');
            fillReportSet(newFinanceReportItems, 'financev2.chargeAdvanceReportSet', 'ChargeAdvanceReportSet');
            fillReportSet(newFinanceReportItems, 'financev2.dailyCheckReportBussinessIncomeSet', 'DailyCheckReportBussinessIncomeSet', 'financev2');
            // fillReportSet(newFinanceReportItems, 'financev2.dealDetailReportSet', 'DealDetailReportSet', 'financev2');
            fillReportSet(newFinanceReportItems, 'financev2.certificateReportSet', 'CertificateReportSet', 'financev2');
            fillReportSet(newFinanceReportItems, 'financev2.membershipReportSet', 'MembershipReportSet', 'financev2');
            fillReportSet(newFinanceReportItems, 'financev2.otherFinanceReportSet', 'OtherFinanceReportSet', 'financev2');
            fillReportSet(newFinanceReportItems, 'financev2.dailyCheckActualPriceReportSetV3', 'DailyCheckActualPriceReportSet', 'financev2');
            fillReportSet(newFinanceReportItems, 'financev2.dealDetailReportSetV3', 'DealDetailReportSet', 'financev2');

        }
        newFinanceReportItems.push(
            { text: '欠费患者', state: 'reportCenter.overduePatient', permissionCode: 'financev2.overduePatientReport', navItemName: 'financev2' },
            { text: '家庭消费统计', state: 'reportCenter.familyConsumption', permissionCode: 'financev2.familyConsumptionRepot', navItemName: 'financev2' }
        );


        /**
         * 旧版
         */
        oldFinanceReportItems = [
            { text: '对账日历', state: 'finance.checkCalendar', permissionCode: 'finance.checkCalendar', navItemName: 'finance' },
            { text: '每日对账', state: 'finance.accountCheck', permissionCode: 'finance.everydayCheck', navItemName: 'finance' },
            { text: '诊所收费明细', state: 'finance.officeChargeDetail', permissionCode: 'finance.officeChargeDetail', navItemName: 'finance' },
            { text: '现金流', state: 'finance.cashFlow', permissionCode: 'finance.cashFlow', navItemName: 'finance' },
            { text: '收入汇总', state: 'finance.chargeSummary', permissionCode: 'finance.chargeSummary', navItemName: 'finance' },
            { text: '账单明细', state: 'finance.chargeDetail', permissionCode: 'finance.chargeDetail', navItemName: 'finance' },
            { text: '项目明细', state: 'finance.chargeItemDetail', permissionCode: 'finance.chargeItemDetail', navItemName: 'finance' }
        ];

        if (moduleOptionProvider.isBigDataEnabled() && !loginContext.isGroup) {
            oldFinanceReportItems = oldFinanceReportItems.concat([
                { text: '账单明细 - 体验版', state: 'finance.customizeChargeDetail', permissionCode: 'finance.chargeDetail', navItemName: 'finance' },
                { text: '项目明细 - 体验版', state: 'finance.customizeChargeItemDetail', permissionCode: 'finance.chargeItemDetail', navItemName: 'finance' }
            ]);
        }
        oldFinanceReportItems = oldFinanceReportItems.concat([
            { text: '折扣报表', state: 'finance.chargeDiscount', permissionCode: 'finance.chargeDiscount', navItemName: 'finance' },
            { text: '欠费患者', state: 'finance.overduePatient', permissionCode: 'finance.overduePatient', navItemName: 'finance' }
        ]);

        if (!isNewPaymentTypeEnabled) {
            oldFinanceReportItems.push({ text: '患者消费统计', state: 'finance.patientConsumption', permissionCode: 'finance.patientConsumption', navItemName: 'finance' });
        }
        oldFinanceReportItems = oldFinanceReportItems.concat([
            { text: '家庭消费统计', state: 'finance.familyConsumption', permissionCode: 'finance.familyConsumption', navItemName: 'finance' },
            { text: '储值卡余额', state: 'finance.membershipBalance', permissionCode: 'finance.membershipBalance', navItemName: 'finance' },
            { text: '储值卡余额变动记录', state: 'finance.membershipSummary', permissionCode: 'finance.membershipSummary', navItemName: 'finance' },
            { text: '积分变动记录', state: 'finance.patientPointSummary', permissionCode: 'finance.patientPointSummary', navItemName: 'finance' },
            { text: '支付宝交易记录', state: 'finance.aliPayOrder', permissionCode: 'finance.aliPayOrderTransaction', navItemName: 'finance' },
            { text: '微信交易记录', state: 'finance.chargePayOrder', permissionCode: 'finance.weixinPayOrderTransaction', navItemName: 'finance' },
            { text: '团购交易记录', state: 'finance.groupByOrder', permissionCode: 'finance.chargeGroupBuyCertificate', navItemName: 'finance' },
            { text: '医保对账表', state: 'finance.yibaoAccountCheck', permissionCode: 'finance.yibaoAccountCheck', navItemName: 'finance' }
        ]);

        var allowStatement = officeSetting.systemConfigs.some(function (d) {
            return d.configName === 'AllowStatement' && d.configValue.toUpperCase() === 'TRUE';
        });

        if (allowStatement) {
            oldFinanceReportItems.push({ text: '对账单查询', state: 'finance.accountStatement', permissionCode: 'managementCenter.accountStatement', navItemName: 'finance' });
        }
        if (moduleOptionProvider.isFinanceCustomizeReportVisible()) {
            oldFinanceReportItems.push({ text: '高级报表', state: 'finance.customizeReport', permissionCode: 'finance.customizeReport', navItemName: 'finance' });
        }

        return [].concat(newFinanceReportItems, oldFinanceReportItems);
    };

    // 营销中心
    var createMarketingManagement = function () {
        $q.all([
            systemConfigUtil.getConfigValue(systemConfigUtil.configKeys.IsEnableGiftCard),
        ]).then(function (values) {
            var isShowGiftCard = values[0];
            var states = [];

            // 营销中心-微信营销
            if (moduleOptionProvider.isSCRMOpen()) {
                $rootScope.isNewWxEnabled = true;
                if (permissionProvider.isAllowed('scrmMgmt.loggin')) {
                    // states.push({ text: '微信营销', state: 'scrmCenter', permissionCode: null });
                }
            }

            // 营销中心-卡券管理
            states.push(
                // { text: '卡券领用明细', state: 'marketingManagement.giftCard.detail', permissionCode: 'membership.cardDetail' },
                // { text: '营销优惠管理', state: 'marketingManagement.giftCard.discount', permissionCode: 'membership.discount|membership.publish' }
            );
            if (isShowGiftCard) {
                states.push({ text: '不记名卡管理', state: 'marketingManagement.giftCard.bearer', permissionCode: 'membership.giftCard' });
            }

            // 营销中心-流量大使
            states.push(
                { text: '渠道服务项目映射', state: 'marketingManagement.appointmentChannel.mapping', permissionCode: null },
                { text: '渠道基础配置', state: 'marketingManagement.appointmentChannel.baseSetting', permissionCode: null },
                { text: '渠道库存配置', state: 'marketingManagement.appointmentChannel.inventorySetting', permissionCode: null }
            );

            // 营销中心-会员管理
            states.push(
                // { text: '会员列表', state: 'marketingManagement.member.list', permissionCode: 'membership.list' },
                // { text: '会员变动记录', state: 'marketingManagement.member.changeLog', permissionCode: 'membership.list' },
                // { text: '储值卡交易明细', state: 'marketingManagement.member.transactionDetail', permissionCode: 'membership.transaction' }
            );

            if (moduleOptionProvider.isMembershipUpgradeEnabled()) {
                states.push({ text: '会员等级申请', state: 'marketingManagement.member.levelApply', permissionCode: 'membership.typeApply' });
            }

            // 营销中心-咨询管理
            states.push(
                { text: '网电咨询', state: 'newPatientManagement.consult.networkList', permissionCode: 'consultCenter.consultList' },
                { text: '现场咨询', state: 'newPatientManagement.consult.list', permissionCode: 'consultCenter.list' },
                { text: '现场咨询任务列表', state: 'newPatientManagement.consult.onSiteList', permissionCode: 'consultCenter.list' }
            );


            // 营销中心-推荐管理
            if (moduleOptionProvider.isReferralEnabled()) {
                var referralItems = [];
                if (!loginContext.isGroup) {
                    // referralItems.push({ text: '概览(营销中心)', state: 'marketingManagement.referralSummary', permissionCode: null });
                }

                // 推荐管理 - 推荐明细 - 被推荐人明细
                referralItems.push(
                    // { text: '推荐人明细', state: 'marketingManagement.referralDetail.referer', permissionCode: null },
                    // { text: '被推荐人明细', state: 'marketingManagement.referralDetail.referee', permissionCode: null }
                );

                // 推荐管理 - 推荐激励明细
                referralItems.push(
                    // { text: '到店激励明细', state: 'marketingManagement.referralReward.arrival', permissionCode: null },
                    // { text: '单笔消费激励明细', state: 'marketingManagement.referralReward.consumption', permissionCode: null },
                    // { text: '累计消费激励明细', state: 'marketingManagement.referralReward.consumptionSum', permissionCode: null }
                );

                states = states.concat(referralItems);
            }
            // 营销中心-回访管理
            states.push({ text: '回访记录', state: 'newPatientManagement.revisit.list', permissionCode: 'ReturnVisitFolder.list' });
            // 营销中心-医患沟通视频
            states.push({ text: '医患沟通视频', state: 'medicalService.patientVideo.list', permissionCode: 'pdCommunication.video' });
            // 营销中心-短信管理
            states.push(
                { text: '短信一览', state: 'officeManagement.sms.dashboard', permissionCode: 'shortMessage.list' },
                { text: '短信记录', state: 'officeManagement.sms.history', permissionCode: 'shortMessage.history' },
                { text: '短信群发', state: 'officeManagement.sms.batch', permissionCode: 'shortMessage.batch' },
                { text: '短信回复', state: 'officeManagement.sms.reply', permissionCode: 'shortMessage.reply' },
                { text: '短信充值', state: 'officeManagement.sms.charge', permissionCode: 'shortMessage.charge' },
                { text: '短信统计', state: 'officeManagement.sms.statistics', permissionCode: 'shortMessage.statistics' },
                { text: '短信自动发送', state: 'officeManagement.sms.autoRule', permissionCode: 'shortMessage.charge' }
            );

            // menuSearchList = menuSearchList.concat(states);
        });
    };

    // 诊所中心
    var createOfficeManagement = function () {
        var states = [];

        /**
         * 诊所中心 - 医疗质控
         */
        var medicalQualityItems = [
            { text: '全部病历', state: 'medicalrecordCenter.allEMR', permissionCode: 'patientCenter.emrSearch' },
        ];
        if (loginContext.providerJob === '医生') {
            medicalQualityItems.push({ text: '待办病历', state: 'pendingMedicalrecord', permissionCode: null });
        }
        if (moduleOptionProvider.isNewMedicalExamEnabled()) {
            medicalQualityItems.push({ text: '检查申请', state: 'medicalExam.list', permissionCode: 'medicalExam.applicationList' })
        }
        states = states.concat(medicalQualityItems);

        /**
         * 诊所中心 - 技加工
         */
        states.push(
            { text: '订单跟踪', state: 'dentalLab.orderTrack', permissionCode: 'dentalLab.order' },
            { text: '结算管理', state: 'dentalLab.settlement', permissionCode: 'dentalLab.order.completeSettle' },
            { text: '厂商管理', state: 'dentalLab.factory', permissionCode: 'dentalLab.factory' },
            { text: '项目维护', state: 'dentalLab.product', permissionCode: 'dentalLab.product' },
            { text: '项目导入', state: 'dentalLab.import', permissionCode: 'dentalLab.product' }
        );

        /**
         * 诊所中心 - 员工管理
         */
        states.push(
            { text: '员工管理', state: 'officeManagement.staff.list', permissionCode: 'setting.provider' },
            { text: '角色管理', state: 'officeManagement.staff.role', permissionCode: 'setting.role' }
        );
        if (moduleOptionProvider.isPartnerMgmtEnabled() && loginContext.isGroup) {
            states.push({ text: '外部账号管理', state: 'officeManagement.staff.partnerAccountManagement', permissionCode: 'setting.partnerUserManagement' })
        }
        // 人员交接
        states.push({ text: '人员交接', state: 'officeManagement.handover.patient', permissionCode: 'setting.patientHandOver' });
        if (officeSetting && officeSetting.isDeductionChargeEnabled === true) {
            states.push({ text: '划扣执行交接', state: 'officeManagement.handover.chargeDeduction', permissionCode: 'setting.chargeDeductionHandOver' });
        }
        // 排班考勤
        if (moduleOptionProvider.isProviderSchedule3Enabled()) {
            states.push(
                { text: '周排班', state: 'officeManagement.schedule.weekly', permissionCode: 'schedule.doctor' },
                { text: '月排班', state: 'officeManagement.schedule.monthly', permissionCode: 'schedule.doctor' },
                { text: '公司排班概览', state: 'officeManagement.schedule.weeklyBrowse', permissionCode: 'schedule.tenant' },
                { text: '固定排班设置', state: 'officeManagement.schedule.fixed', permissionCode: 'schedule.doctor' },
                { text: '打卡记录', state: 'officeManagement.schedule.attendanceList', permissionCode: 'schedule.attendanceList' },
                { text: '考勤报表', state: 'officeManagement.schedule.attendanceDayList', permissionCode: 'schedule.attendanceList' }
            );
        } else {
            states.push(
                { text: '诊所医生排班', state: 'officeManagement.schedule.doctor', permissionCode: 'schedule.doctor' },
                { text: '公司排班概览', state: 'officeManagement.schedule.tenant', permissionCode: 'schedule.tenant' },
                { text: '打卡记录', state: 'officeManagement.schedule.attendanceList', permissionCode: 'schedule.attendanceList' },
                { text: '考勤报表', state: 'officeManagement.schedule.attendanceDayList', permissionCode: 'schedule.attendanceList' }
            );
        }
        // 号源管理
        if (moduleOptionProvider.isAppointmentResourceEnabled()) {
            states.push(
                { text: '号源规则配置', state: 'officeManagement.appointmentResource.rule', permissionCode: 'setting.providerResourceView' },
                { text: '号源概览', state: 'officeManagement.appointmentResource.view', permissionCode: 'setting.appointmentResourceView' }
            );
        }



        /**
         * 诊所中心 - 诊所运营
         */
        states.push(
            { text: '审批管理', state: 'officeManagement.businessRule.workflowApproval', permissionCode: 'workflowManagement.approval' },
            { text: '门诊信息', state: 'officeManagement.orgchain.offices', permissionCode: 'tenantSettings.office' },
            { text: '配置分发', state: 'officeManagement.orgchain.baseData', permissionCode: 'organizationManagement.baseData' },
            { text: '数据共享', state: 'officeManagement.orgchain.businessData', permissionCode: 'organizationManagement.baseData' }
        );

        if (isLcCrmEnabled) {
            states.push(
                //{ text: '诊所账户', state: 'officeManagement.officeAccount.setting', permissionCode: 'tenantSettings.account' },
                // { text: '账户验收', state: 'officeManagement.accountAcceptance.setting', permissionCode: 'setting.accountAcceptance' }
            );
        }

        /**
         * 支出管理
         */
        // states.push({ text: '支出管理', state: 'expendCenter.list', permissionCode: 'expendCenter.list' });

        /**
         * 安全管理
         */
        states.push(
            { text: '账号安全', state: 'officeManagement.accountSecurity.list', permissionCode: 'security.loginLog' },
            { text: '患者数据', state: 'officeManagement.patientSecurity.data', permissionCode: 'security.dataSetting' },
            { text: '操作日志', state: 'officeManagement.operationSecurity.log', permissionCode: 'security.operationLog' }
        );
        if (moduleOptionProvider.isDeviceMgmtEnabled()) {
            states.push({ text: '设备安全', state: 'officeManagement.deviceSecurity', permissionCode: 'deviceSecurity.management|deviceSecurity.application' });
        }

        /**
         * 备忘管理
         */
        states.push({ text: '备忘查询', state: 'memo.list', permissionCode: 'memoManagement.record' });
        return states;
    };

    // CSSD
    var createCssd = function () {
        return [
            { text: '基础信息(CSSD)', state: 'cssd.baseData', permissionCode: null },
            { text: '业务中心(CSSD)', state: 'cssd.businessCenter', permissionCode: null },
            { text: '借入借出(CSSD)', state: 'cssd.borrowLog', permissionCode: null }
        ];
    };

    // 领健商城
    var createMallCenter = function () {
        // return [{ text: '领健商城', state: 'mallCenter', permissionCode: null }];
    };

    // 增值服务
    var createOpenPlatformCenter = function () {
        return [
            // { text: '增值服务', state: 'new', permissionCode: null, param: { route: 'enterpriseCenter.services' } }
        ];
    };

    // 系统设置
    var createSystemSetting = function () {
        var states = [];

        /**
         * 预约中心设置
         */
        states.push(
            { text: '预约规则', state: 'systemSetting.appointment.rule', permissionCode: 'setting.office&settings.rule' },
            { text: '预约项目', state: 'systemSetting.appointment.item', permissionCode: 'setting.appointment' },
            { text: '预约看板', state: 'systemSetting.appointment.scheduler', permissionCode: 'setting.office&settings.rule' },
            { text: '预约提醒服务', state: 'systemSetting.appointment.reminding', permissionCode: 'setting.office&settings.rule' }
        );

        states.push(
            { text: '叫号设置', state: 'systemSetting.triage.calling', permissionCode: 'setting.office' },
            { text: '挂号设置', state: 'systemSetting.triage.checkInSetting', permissionCode: 'setting.systemsetting' }
        );

        /**
         * 患者中心设置
         */
        // 患者必填项
        states.push(
            { text: '新建患者必填项', state: 'systemSetting.patientField.newPatient', permissionCode: 'setting.office&settings.newPatientInfo' },
            { text: '网电新建患者必填项', state: 'systemSetting.patientField.onlineConsultant', permissionCode: 'setting.office&settings.onlineConsultCreateInfo' },
            { text: '挂号必填项设置', state: 'systemSetting.patientField.checkInSetting', permissionCode: 'setting.office&settings.checkInInfo' }
        );
        // 标签设置
        states.push({ text: '标签设置', state: 'systemSetting.patientTag.management', permissionCode: 'managementCenter.tagCenter' });
        // 随访设置
        states.push(
            { text: '随访模板', state: 'systemSetting.patientFollowup.template', permissionCode: null },
            { text: '随访内容模板', state: 'systemSetting.patientFollowup.contentTemplate', permissionCode: 'followup.content' },
            { text: '随访结果模板', state: 'systemSetting.patientFollowup.resultTemplate', permissionCode: 'followup.result' },
            { text: '自动随访规则', state: 'systemSetting.patientFollowup.autoRule', permissionCode: null }
        );

        /**
         * 营销中心设置
         */
        // 推荐管理设置
        // states.push({ text: '到店激励', state: 'systemSetting.marketingReferral.arrival', permissionCode: null });
        if (moduleOptionProvider.isReferralPaymentRuleEnabled()) {
            states.push(
                // { text: '单笔消费激励', state: 'systemSetting.marketingReferral.payment', permissionCode: null },
                // { text: '累计消费激励', state: 'systemSetting.marketingReferral.totalPayment', permissionCode: null }
            );
        }
        // 会员管理设置
        states.push(
            // { text: '会员类型设置', state: 'systemSetting.memberTypes.management', permissionCode: 'membership.categroy' },
            // { text: '会员卡号设置', state: 'systemSetting.memberTypes.cardNumberConfig', permissionCode: 'setting.office' },
            // { text: '积分规则', state: 'systemSetting.memberTypes.point', permissionCode: 'setting.office' }
        );
        // 回访设置
        states.push({ text: '自动回访规则', state: 'systemSetting.patientRevisit.autoRule', permissionCode: 'ReturnVisitFolder.list' });
        // 咨询设置
        states.push({ text: '成交意愿', state: 'systemSetting.patientConsultant.intention', permissionCode: null });

        /**
         * 进销存设置
         */
        // 中间节点没有仓库管理，所以没有仓库设置
        var condition = moduleOptionProvider.isNewInventoryOpen() // 新供应链开关
            && ((loginContext.isGroup && loginContext.isRootGroup) // 是rootGroup
                || !loginContext.isGroup // 不是群组
                || (loginContext.isGroup // 群组但不是直营
                    && !loginContext.isRegularChain));
        if (condition) {
            // states.push({ text: '业务规则设置(进销存)', state: 'systemSetting.supplychainRule.management', permissionCode: 'setting.office&settings.supplychain' });
        }
        states.push({ text: '物品信息设置', state: 'systemSetting.productBasicDataManagement', permissionCode: 'product.productInfo' });

        /**
         * 诊所中心设置
         */
        // 排班考勤
        states.push(
            { text: '班次配置', state: 'systemSetting.staffManagement.scheduleSetting', permissionCode: 'schedule.rule' },
            { text: '考勤配置', state: 'systemSetting.staffManagement.attendanceSetting', permissionCode: 'schedule.attendanceConfig' }
        );
        // 审批管理设置
        states.push({ text: '审批管理设置', state: 'systemSetting.businessManagement.approvalSetting', permissionCode: 'setting.approval' });
        // 支出设置
        // states.push({ text: '支出设置', state: 'new', permissionCode: 'setting.office', param: { route: 'systemSetting.office.expend-center' } });
        // 诊断项目
        states.push({ text: '诊断项目', state: 'systemSetting.medicalDiagnosis.management', permissionCode: 'setting.diagnosis' });
        if (!loginContext.isProfessional) {
            states.push({ text: '治疗计划项目配置', state: 'systemSetting.medicalDiagnosis.treatmentPlan', permissionCode: 'setting.appointment' });
        }
        // 病历设置
        states.push(
            { text: '病历配置', state: 'systemSetting.medicalRecord.settings', permissionCode: 'setting.emrtemplate' },
            { text: '病历模板', state: 'systemSetting.medicalRecord.template', permissionCode: 'setting.emrtemplate' },
            { text: '词条配置', state: 'systemSetting.medicalRecord.templateItem', permissionCode: 'setting.emrtemplate' }
        );
        // 技加工设置
        if (moduleOptionProvider.isNewDentalLabEnabled()) {
            // states.push({ text: '技加工配置', state: 'systemSetting.dentalLab.settings', permissionCode: 'patientOutProcess.config' });
        }
        if (moduleOptionProvider.enableOrthdonticModule()) {
            states.push(
                // { text: '正畸计划配置', state: 'orthdontic.settings.plan', permissionCode: 'setting.orthdontic' },
                // { text: '正畸过程配置', state: 'orthdontic.settings.process', permissionCode: 'setting.orthdontic' }
            );
        }
        // 通用设置
        states.push(
            { text: '诊所发票信息', state: 'systemSetting.officeManagementMisc.invoice', permissionCode: 'setting.office' },
            { text: '诊室设置', state: 'systemSetting.officeManagementMisc.operatory', permissionCode: 'setting.operatory' },
            { text: '业务规则设置', state: 'systemSetting.officeManagementMisc.businessRule', permissionCode: 'setting.office&settings.rule' },
            { text: '基础项目', state: 'systemSetting.officeManagementMisc.systemSetting', permissionCode: 'setting.systemsetting' },
            { text: '自由项配置', state: 'systemSetting.officeManagementMisc.freefieldSetting', permissionCode: 'setting.office' },
            { text: '今日工作配置', state: 'systemSetting.officeManagementMisc.workbenchSetting', permissionCode: 'setting.office&settings.todayWork' }
            // { text: '叫号设置', state: 'systemSetting.officeManagementMisc.calling', permissionCode: 'setting.office' }
        );
        if (loginContext.isRoot) {
            states.push({ text: '总部业务设置', state: 'systemSetting.officeManagementMisc.permissionSetting', permissionCode: null });
        }

        /**
         * 收费设置
         */
        // 收费类型设置
        // states.push({ text: '收费类型设置', state: 'systemSetting.chargeField.setting', permissionCode: 'setting.office&settings.chargeInfo' });
        // 收费项目设置
        if (officeSetting && officeSetting.isDeductionChargeEnabled) {
            // states.push({ text: '划扣方案设置', state: 'systemSetting.chargeItem.deductionPlan', permissionCode: 'setting.chargeitemBrowse' });
        }
        states.push(
            // { text: '收费项目设置', state: 'systemSetting.chargeItem.setting', permissionCode: 'setting.chargeitemBrowse' },
            // { text: '收费项目必填项', state: 'systemSetting.chargeItem.requirement', permissionCode: 'setting.office&settings.baseData' },
            // { text: '收费项导入', state: 'systemSetting.chargeItem.import', permissionCode: 'dataImport.chargeItem' }
        );
        if (chargeItemFreeField && chargeItemFreeField.length) {
            // states.push({ text: '收费项目自由项配置', state: 'systemSetting.chargeItem.freefield', permissionCode: 'setting.chargeitemBrowse' });
        }
        states.push(
            // { text: '费用类型配置', state: 'systemSetting.chargeItem.chargeType', permissionCode: 'setting.chargeitemBrowse' },
            // { text: '收费类别配置', state: 'systemSetting.chargeItem.chargeCategory', permissionCode: 'setting.chargeitemBrowse' },
            // { text: '收费套餐设置', state: 'systemSetting.chargeItem.chargePackageSetting', permissionCode: 'setting.chargeitemBrowse' }
        );
        // 支付方式设置
        // states.push({ text: '支付方式配置', state: 'systemSetting.chargePayment.method', permissionCode: 'setting.chargeitemBrowse' });
        if (thirdPartyPayDeviceTabVisible) {
            // states.push({ text: '收银设备管理', state: 'systemSetting.chargePayment.thirdPartyDevices', permissionCode: null });
        }
        return states;
    };

    var createOthers = function () {
        //其他项，不在左边导航栏显示
        return [];
    };


    /**
     * 获取所有菜单列表
     */
    var initMenus = function () {
        if (loginContext.isGroup) {
            var isShow = loginContext.roles.indexOf('网电咨询师') > -1 || loginContext.roles.indexOf('网电主管') > -1;
            if (loginContext.dashboardType === 'WebPhoneConsultant' || isShow) {
                menuSearchList = menuSearchList.concat(createDashboard());
            } else if (loginContext.dashboardType === 'Inventory' && loginContext.isRootGroup && moduleOptionProvider.isGroupInventoryEnabled()) {
                menuSearchList = menuSearchList.concat(createDashboard());
            }
        } else {
            if (loginContext.dashboardType) {
                menuSearchList = menuSearchList.concat(createDashboard());
            }
        }

        // 领健商城 根据配置决定是否显示商城
        if (moduleOptionProvider.isMallOpen()) {
            if (permissionProvider.isAllowed('tradingPlatform.list')) {
                menuSearchList = menuSearchList.concat(createMallCenter());
            }
        }

        // 根据配置决定是否显示增值服务
        if (moduleOptionProvider.isOpenPlatformEnabled()) {
            menuSearchList = menuSearchList.concat(createOpenPlatformCenter());
        }

        // CSSD
        if (moduleOptionProvider.isCssdEnabled()) {
            menuSearchList = menuSearchList.concat(createCssd());
        }

        // 同步处理
        menuSearchList = menuSearchList.concat(
            createPatientHost(),
            createScheduleCenter(),
            createReportCenter(),
            createOfficeManagement(),
            createSystemSetting(),
            createOthers()
        );

        // 异步处理
        createSupplychain();
        createMarketingManagement();
    };

    var fillReportSet = function (navItems, setState, setName, navItemName) {
        var reportSet = _(reportSetConfigs).find(function (c) {
            return c.name === setName;
        });
        if (reportSet && reportSet.reports && reportSet.reports.length > 0) {
            var setPermission = null;
            if (_(reportSet.reports).every(function (r) { return r.permissionCode; })) {
                setPermission = _(reportSet.reports).pluck('permissionCode').join('|');
            }
            navItems.push({ text: reportSet.displayName, state: setState, permissionCode: setPermission, navItemName: navItemName });
        }
    };

    var officeSetting;
    var chargeItemFreeField;
    var initialize = function () {
        if (!dataDicSvc.reportSetConfigDic) {
            dataDicSvc.initialize();
        }

        $q.all([
            systemConfigSvc.getIsLcCrmEnabled(),
            dataDicSvc.reportSetConfigDic.load(),
            dataDicSvc.officeSettingDic.load(),
            dataDicSvc.chargeItemFreeFieldDic.load(),
        ]).then(function (data) {
            isLcCrmEnabled = data[0];
            reportSetConfigs = data[1];
            officeSetting = data[2];
            chargeItemFreeField = data[3];

            getOfficeOption().then(function () {
                initMenus();
            });
        });
    };

    // 是否打开检查
    var isMedicalExamOpen;
    var isNeedCheckAgreePrice;
    var isNewPaymentTypeEnabled;
    var enableConsultantDiagnose;
    var thirdPartyPayDeviceTabVisible;
    var getOfficeOption = function () {
        var deferred = $q.defer();
        $q.all([
            officeOptionSvc.getOfficeOption(officeOptionSvc.optionKeys.IsMedicalExamOpen),
            officeOptionSvc.getOfficeOption(officeOptionSvc.optionKeys.IsNeedCheckAgreePrice),
            officeOptionSvc.getOfficeOption(officeOptionSvc.optionKeys.IsNewPaymentTypeEnabled),
            officeOptionSvc.getOfficeOption(officeOptionSvc.optionKeys.EnableConsultantDiagnose),
            chargeSvc.getThirdPartyPayConfig(),
        ]).then(function (values) {
            isMedicalExamOpen = values[0];
            isNeedCheckAgreePrice = values[1];
            isNewPaymentTypeEnabled = values[2];
            enableConsultantDiagnose = values[3];
            thirdPartyPayDeviceTabVisible = values[4].data && values[4].data.length > 0;
            deferred.resolve();
        });
        return deferred.promise;
    };

    (function () {
        $scope.searchText = '';
        $scope.menus = [];
        $scope.isShow = false;
        $scope.getMatchText = getMatchText;
        $scope.filterMenus = filterMenus;

        initialize();
    })();
}]);

ares3Module.directive('ares3SideBarSearch',
['$timeout', 'appNav',
function($timeout, appNav) {
    'use strict';

    return {
        restrict: 'E',
        templateUrl: '/app-ares3/framework/ares3-side-bar-search/ares3-side-bar-search.html',
        replace: false,
        controller: 'Ares3SideBarSearchController',
        link: function($scope, element, attrs) {
            var onDocumentClick = function(event) {
                var searchBox = angular.element(event.target).parents('.ares3-side-bar-search-container').find('.ares3-side-bar-search-box');
                if (searchBox.length === 0) {
                    document.removeEventListener('click', onDocumentClick);
                    $timeout(function () {
                        $scope.isShow = false;
                        $scope.searchText = '';
                        destroySidebarSearchScroll();
                    });
                }
            };

            /**
             * 显示搜索面板
             * @param e
             */
            var onShowSearch = function(e) {
                e.stopPropagation();
                if ($scope.isShow) return;
                $scope.isShow = true;
                $scope.menus = [];
                document.addEventListener('click', onDocumentClick);
                Ares.sensors.track('NewMenuSearch', {
                    OperationType: '点击搜索菜单',
                });
            };

            /**
             * 搜索
             */
            var onSearch = function() {
                $scope.filterMenus($scope.searchText || '');
                $timeout(function () {
                    createSidebarSearchScroll();
                }, 0, false);
            };

            /**
             * 创建搜索菜单面板滚动条
             */
            var createSidebarSearchScroll = function() {
                var $ = $ || window.jQuery;
                if ($.fn.mCustomScrollbar) {
                    destroySidebarSearchScroll();
                    if ($('.ares3-side-bar-search__list').length > 0) {
                        $('.ares3-side-bar-search__list-scroll').mCustomScrollbar({
                            scrollButtons: {
                                enable: false
                            },
                            autoHideScrollbar: true,
                            scrollInertia: 300,
                            advanced: {
                                updateOnContentResize: true
                            }
                        });
                    }
                }
            };

            var destroySidebarSearchScroll = function() {
                $('.ares3-side-bar-search__list-scroll').mCustomScrollbar("destroy");
            };

            /**
             * 点击菜单选项
             * @param menu
             */
            var onMenuItem = function(menu) {
                $scope.isShow = false;
                $scope.searchText = '';
                if (menu && menu.state) {
                    menu.state === 'new' ? appNav.goToState(menu.state, menu.param) : appNav.goToState(menu.state);
                }
                Ares.sensors.track('NewMenuSearch', {
                    OperationType: '跳转搜索结果',
                });
            };

            (function initialize() {
                $scope.onShowSearch = onShowSearch;
                $scope.onSearch = onSearch;
                $scope.onMenuItem = onMenuItem;
            })();
        }
    };
}]);

frameworkModule.directive('ares3TopBar',
    ['$log', '$timeout', '$interval', '$document', 'eventAggregator', '$rootScope',
        '$q', 'loginToken', 'permissionProvider', 'messageCenterSvc', 'userSvc', 'appNav',
        '$modal', 'userOptionSvc', 'sessionCache', '$state', 'loginContext', 'patientUtil',
        'aresNotification', 'speechCallSvc', 'officeOptionSvc', 'practiceSvc', 'cardReaderService',
        'membershipSvc', 'systemConfigSvc', 'customerServiceSvc', '$window', 'tenantSvc', 'enums',
        'aresDialog', 'aresModalShelf', 'dataDicSvc', 'officeOptionUtil', 'localSvc', 'hebePortal',
        'officeUtil', 'aresYibaoLocalUtil', 'systemMessageSvc', '$injector', 'officeSvc', 'moduleUtil',
        function ($log, $timeout, $interval, $document, eventAggregator, $rootScope,
            $q, loginToken, permissionProvider, messageCenterSvc, userSvc, appNav,
            $modal, userOptionSvc, sessionCache, $state, loginContext, patientUtil,
            aresNotification, speechCallSvc, officeOptionSvc, practiceSvc, cardReaderService, membershipSvc,
            systemConfigSvc, customerServiceSvc, $window, tenantSvc, enums,
            aresDialog, aresModalShelf, dataDicSvc, officeOptionUtil, localSvc, hebePortal,
            officeUtil, aresYibaoLocalUtil, systemMessageSvc, $injector, officeSvc, moduleUtil) {
            'use strict';

            return {
                restrict: 'E',
                templateUrl: '/app-ares3/framework/ares3-top-bar/ares3-top-bar.html',
                replace: true,
                controller: 'Ares3SideBarController',

                link: function ($scope, element, attrs) {
                    var globalEventHandler = Ares.globalEventUtil($document);
                    var isFirstCount = true;
                    var messageFilterReadCnt = 0;
                    var speechCallToken = null;
                    var keys = {
                        weChatBizMessageCode: 'scheduleCenter.weixinApplyList',
                        unChargeMessageCode: 'dashBoard.uncharge',
                        stockRemindMessageCode: 'inventoryBrowse.stockStatus',
                        shortMessageBackCode: 'shortMessage.reply',
                        shortMessageRemindCode: 'shortMessage.charge',
                        workflowReminderCode: 'workflowManagement.approval',
                        RemindTimeOutCode: 'remindTimeOut',
                        memoMessageCode: 'memoManagement.record',
                        strongRemind: 'scheduleCenter.strongRemind',
                        editMedicalRecordCode: 'patientMedicalRecord.create'
                    };
                    var bizMessageCodeCache = sessionCache.getCache(sessionCache.keys.MessageCenterIgnoredBizMessageCode);


                    var initBizMessageCodeCache = function () {
                        var cachedBizMessageCode = bizMessageCodeCache.loadObject();
                        if (cachedBizMessageCode) {
                            _.extend($scope.bizMessageCodes, cachedBizMessageCode);
                        }
                    };

                    var initView = function () {
                        // Add class everytime a mouse pointer hover over it
                        var hoverTimeout;
                        $('.nav-sidebar > li').hover(function () {
                            clearTimeout(hoverTimeout);
                            $(this).siblings().removeClass('nav-hover');
                            $(this).addClass('nav-hover');
                        }, function () {
                            var $self = $(this);
                            hoverTimeout = setTimeout(function () {
                                $self.removeClass('nav-hover');
                            }, 200);
                        });
                        $('.nav-sidebar > li .children').hover(function () {
                            clearTimeout(hoverTimeout);
                            $(this).closest('.nav-parent').siblings().removeClass('nav-hover');
                            $(this).closest('.nav-parent').addClass('nav-hover');
                        }, function () {
                            var $self = $(this);
                            hoverTimeout = setTimeout(function () {
                                $(this).closest('.nav-parent').removeClass('nav-hover');
                            }, 200);
                        });

                        createSideScroll();
                        if (angular.element('body').hasClass('submenu-visible')) {
                            $('#ares3-top-bar').css({ 'left': '200px' });
                        }
                        element.find('#ares3-topbar-help-icon').tooltip();
                    };

                    var setMessageItem = function (messageData, item, menuClass, menuBigClass, state) {
                        messageData.push({
                            menuName: item.title,
                            menuClass: menuClass,
                            menuBigClass: menuBigClass,
                            state: state,
                            createTimeText: item.createTimeText,
                            createTimeFormatText: item.createTimeFormatText,
                            count: item.count,
                            isShow: true,
                            isShowDel: false,
                            content: item.content,
                            messageItems: item.messageItems
                        });
                    };

                    var initMessages = function (messages) {
                        var messageData = [];
                        if (messages) {
                            $.each(messages, function (index, item) {
                                if (item.messageType == '系统公告') {
                                    setMessageItem(messageData, item, '系统公告', '系统公告', '');
                                } else if (item.messageType == '网络预约') {
                                    setMessageItem(messageData, item, '网络预约', '业务提醒', 'dashBoard.appointApply');
                                } else if (item.messageType == '收费提醒') {
                                    setMessageItem(messageData, item, '收费提醒', '业务提醒', 'dashBoard.uncharge');
                                } else if (item.messageType == '库存预警') {
                                    setMessageItem(messageData, item, '库存预警', '预警信息', 'inventoryBrowse.stockStatus');
                                } else if (item.messageType == '短信预警') {
                                    setMessageItem(messageData, item, '短信预警', '预警信息', 'shortMessage.charge');
                                } else if (item.messageType == '短信回复') {
                                    setMessageItem(messageData, item, '短信回复', '业务提醒', 'shortMessage.feedback');
                                } else if (item.messageType == '审批提醒') {
                                    setMessageItem(messageData, item, '审批提醒', '业务提醒', 'workflowManagement.approval');
                                } else if (item.messageType == '备忘提醒') {
                                    setMessageItem(messageData, item, '备忘提醒', '业务提醒', 'memo.list');
                                } else if (item.messageType == '病历打回') {
                                    setMessageItem(messageData, item, '病历打回', '业务提醒', 'medicalrecordCenter.myEmr');
                                }
                            });
                        }
                        return messageData;
                    }

                    var refreshView = function (navItem) {
                        if (!navItem.subItems) {
                            $scope.navigate(navItem);
                        }
                        $timeout(function () {
                            refreshSideScroll();
                        }, 200);
                    };

                    var linkHelpPage = function () {
                        var helpPageUrl = "https://lccs.kf5.com/hc/kb/article/1379582";
                        // get help page sso url
                        tenantSvc.getHelpPageSso().then(function (result) {
                            var openUrl = helpPageUrl;
                            if (result.data) {
                                openUrl = result.data + "&return_to=" + helpPageUrl;
                            }
                            window.open(openUrl);
                        });
                        addSensorTrack('帮助');
                    };

                    var getLocationUrl = function () {
                        var url = window.location.hash;
                        var index = url.indexOf('?');
                        if (index > -1) {
                            url = url.substring(0, index);
                        }
                        return url;
                    };

                    var getHelpPageUrl = function (locationUrl, helpPages) {
                        var helpPageUrl = 'https://lccs.kf5.com';
                        var helpPage = _.find(helpPages, { 'saasPageUrl': locationUrl });
                        if (!helpPage) {
                            var lastIndex = locationUrl.lastIndexOf('/');
                            if (lastIndex > -1) {
                                locationUrl = locationUrl.substring(0, lastIndex);
                                helpPageUrl = getHelpPageUrl(locationUrl, helpPages);
                            }
                        } else {
                            helpPageUrl = helpPage.helpPageUrl;
                        }
                        return helpPageUrl;
                    };

                    var hideThis = function (message) {
                        message.isShow = false;
                    }

                    var goToNavigate = function (message) {
                        message.isShow = message.count > 0;
                        if (message.menuBigClass == '系统公告') {
                            message.count = message.count - 1;
                            var items = _.filter(message.messageItems, { hasRead: false });

                            if (items) {
                                $scope.readMessage(items[items.length - 1].id);

                                loadMessages();
                            }
                        }
                        else {
                            message.count = 0;

                            switch (message.menuClass) {
                                case "网络预约":
                                case "收费提醒":
                                    if (loginContext.dashboardType == 'FrontDesk') {
                                        appNav.switchState(message.state, { status: message.state });
                                    }
                                    else {
                                        //网络预约
                                        if (window.Ares3) {
                                            appNav.goToState('new', { route: 'appointment.apply' });
                                        } else {
                                            appNav.goToState('apptMgmt.weixinApplyList');
                                        }
                                    }
                                    break;
                                case "库存预警":
                                    if (permissionProvider.isAllowed(keys.stockRemindMessageCode)) {
                                        appNav.goToState('supplychain.inventory.stockRemind');
                                    }
                                    break;
                                case "备忘提醒":
                                case "短信预警":
                                case "病历打回":
                                    appNav.goToState(message.state);
                                    break;
                                case "短信回复":
                                    messageCenterSvc.updateBizMessageLog(1);
                                    appNav.goToState(message.state);
                                    break;
                                case "审批提醒":
                                    messageCenterSvc.updateBizMessageLog(6).then(function () {
                                        var currentPermissionCodes = [];
                                        currentPermissionCodes.push(keys.workflowReminderCode);
                                        loadRefreshMessage(currentPermissionCodes);
                                    });
                                    appNav.goToState(message.state);
                                    break;
                                default:
                                    break;
                            }
                        }
                    };

                    var goToApptApply = function (applyId) {
                        Ares.sensors.track('webclick', {
                            'OperationType': '查看网络预约任务',
                            'EventType': '网络预约操作'
                        });
                        appNav.goToDashBoardApply("", applyId);
                    };

                    var setMessageHide = function (messageType) {
                        var message = _.find($scope.messageData, { menuClass: messageType });

                        message.isShow = false;
                    };

                    var initMessage = function () {
                        userOptionSvc.checkMsgNotTroubleMode().then(function (value) {
                            if ($scope.isMessageNotDisturbDisalbed) {
                                $scope.notTrouble = false;
                            } else {
                                $scope.notTrouble = value;
                            }
                        });

                        $scope.$on('to-parent-notTrouble', function (event, data) {
                            $scope.notTrouble = data;
                        });

                        $scope.$on('to-parent-messages', function (event, data) {
                            keepIsShow($scope.messageData, data, '系统公告');
                            keepIsShow($scope.messageData, data, '网络预约');
                            keepIsShow($scope.messageData, data, '收费提醒');
                            keepIsShow($scope.messageData, data, '审批提醒');
                            keepIsShow($scope.messageData, data, '备忘提醒');
                            keepIsShow($scope.messageData, data, '病历打回');
                            $scope.messageData = data;
                        });

                        loadMessages();

                        messageCenterSvc.getTimerSeconds().success(function (seconds) {
                            var minInterval = 600;
                            seconds = seconds && seconds > minInterval ? seconds : minInterval;
                            var getMessage = $interval(function () {
                                loadMessages();
                            }, seconds * 1000);
                        });
                    }

                    var keepIsShow = function (oldData, newData, messageType) {
                        var oldMessage = _.find(oldData, { menuClass: messageType });
                        var newMessage = _.find(newData, { menuClass: messageType });

                        if (newMessage && oldMessage && !newMessage.isChangeShow) {
                            newMessage.isShow = oldMessage.isShow;
                        }
                    };

                    var setFilterMessageItem = function (messageData, messages, messageType, key) {
                        var message = _.filter(messages, { messageType: messageType });
                        var codeCache = _.filter($scope.bizMessageCodes, { code: key });

                        if (message.length > 0) {
                            if (codeCache.length > 0 && codeCache[0].time < message[0].createTimeText || codeCache.length == 0) {
                                if (!messageData) {
                                    messageData = [];
                                }

                                var oldMessage = _.find(messageData, { menuClass: messageType });
                                if (oldMessage) {
                                    oldMessage.createTimeText = message[0].createTimeText;
                                    oldMessage.createTimeFormatText = message[0].createTimeFormatText;
                                    oldMessage.count = message[0].count;
                                    oldMessage.content = message[0].content;
                                    oldMessage.messageItems = message[0].messageItems;
                                } else {
                                    messageData.push(message[0]);
                                }
                            }
                        }
                    };

                    var setApplyMessageItem = function (messages) {
                        _.each(messages, function (item) {
                            var createTime = new Date(item.createTime);
                            item.isOver30m = ((Ares.today() - createTime) / 1000 / 60) > 30 ? true : false;
                        });
                    };

                    var setFilterTimeOutMessageItem = function (messageData, messages, messageType, key, timeOutKey) {
                        var message = _.filter(messages, { messageType: messageType });
                        var codeCache = _.filter($scope.bizMessageCodes, { code: key });
                        var remindTimeOutCodeCache = _.filter($scope.bizMessageCodes, { code: timeOutKey });
                        if (message.length > 0 && remindTimeOutCodeCache.length == 0) {
                            if (codeCache.length > 0 && codeCache[0].time < message[0].createTimeText || codeCache.length == 0) {
                                if (!messageData) {
                                    messageData = [];
                                }

                                messageData.push(message[0]);
                            }
                        }
                    };

                    var loadMessages = function () {
                        permissionProvider.loadPermissions().then(function () {
                            initBizMessageCodeCache();
                            var permissionCodes = new Array();

                            if (permissionProvider.isAllowed(keys.weChatBizMessageCode) || loginContext.dashboardType) {
                                permissionCodes.push(keys.weChatBizMessageCode);
                            }
                            if (permissionProvider.isAllowed(keys.shortMessageBackCode)) {
                                permissionCodes.push(keys.shortMessageBackCode);
                            }
                            if (permissionProvider.isAllowed(keys.shortMessageRemindCode)) {
                                permissionCodes.push(keys.shortMessageRemindCode);
                            }
                            if (loginContext.dashboardType == 'FrontDesk') {
                                permissionCodes.push(keys.unChargeMessageCode);
                                permissionCodes.push(keys.stockRemindMessageCode);
                                if (permissionProvider.isAllowed(keys.strongRemind)) {
                                    permissionCodes.push(keys.strongRemind);
                                }
                            }
                            else if (permissionProvider.isAllowed(keys.stockRemindMessageCode)) {
                                permissionCodes.push(keys.stockRemindMessageCode);
                            }
                            if (permissionProvider.isAllowed(keys.memoMessageCode)) {
                                permissionCodes.push(keys.memoMessageCode);
                            }
                            if (permissionProvider.isAllowed(keys.editMedicalRecordCode)) {
                                permissionCodes.push(keys.editMedicalRecordCode);
                            }
                            permissionCodes.push(keys.workflowReminderCode);

                            loadPermissionMessage(permissionCodes);
                        });
                    };

                    var loadRefreshMessage = function (permissionCodes) {
                        messageCenterSvc.getMessages(permissionCodes).success(function (messages) {
                            //审批提醒
                            setFilterMessageItem($scope.messageData, messages, '审批提醒', keys.workflowReminderCode);
                            setMessageHide('审批提醒');
                            $scope.$broadcast('to-child-messages-count', getMessageCount());
                        });
                    };

                    var loadPermissionMessage = function (permissionCodes) {
                        messageCenterSvc.getMessages(permissionCodes).success(function (messages) {
                            var isCache = false;
                            //系统公告
                            var messageData = _.filter(messages, { messageType: '系统公告' });

                            //网络预约强提醒
                            $scope.apptApplysRemind = _.find(messages, function (item) {
                                return item.messageType === "预约强提醒";
                            });
                            if ($scope.apptApplysRemind && $scope.apptApplysRemind.messageItems) {
                                $scope.checkoutRemind = _.filter($scope.apptApplysRemind.messageItems, function (item) {
                                    return item.title === "核销";
                                });
                                $scope.applyRemind = _.filter($scope.apptApplysRemind.messageItems, function (item) {
                                    return item.title === "预约";
                                });

                                $scope.isShowMoreMessage = ($scope.checkoutRemind && $scope.checkoutRemind.length > 1)
                                    || ($scope.applyRemind && $scope.applyRemind.length > 3);
                                if ($scope.checkoutRemind && $scope.checkoutRemind.length > 1) {
                                    $scope.checkoutRemind = $scope.checkoutRemind.slice(0, 1);
                                }
                                if ($scope.applyRemind && $scope.applyRemind.length > 3) {
                                    $scope.applyRemind = $scope.applyRemind.slice(0, 3);
                                }
                                setApplyMessageItem($scope.applyRemind);

                                if (permissionProvider.isAllowed("scheduleCenter.strongRemind")
                                    && !$scope.isStrongMessageDisabled
                                    && ($scope.enabledApptChannel.includes("wesure") || $scope.enabledApptChannel.includes("alipaybp"))
                                    && (($scope.checkoutRemind && $scope.checkoutRemind.length > 0)
                                        || ($scope.applyRemind && $scope.applyRemind.length > 0))) {
                                    $scope.isShowStrongMessage = true;
                                }
                            }

                            //网络预约
                            setFilterMessageItem(messageData, messages, '网络预约', keys.weChatBizMessageCode);

                            //收费提醒
                            setFilterMessageItem(messageData, messages, '收费提醒', keys.unChargeMessageCode);

                            //库存预警
                            setFilterTimeOutMessageItem(messageData, messages, '库存预警', keys.shortMessageRemindCode, keys.RemindTimeOutCode);

                            //短信预警
                            setFilterTimeOutMessageItem(messageData, messages, '短信预警', keys.shortMessageRemindCode, keys.RemindTimeOutCode);

                            //短信回复
                            setFilterMessageItem(messageData, messages, '短信回复', keys.shortMessageBackCode);

                            //审批提醒
                            setFilterMessageItem(messageData, messages, '审批提醒', keys.workflowReminderCode);

                            //备忘提醒
                            setFilterMessageItem(messageData, messages, '备忘提醒', keys.memoMessageCode);

                            //病历打回
                            setFilterMessageItem(messageData, messages, '病历打回', keys.editMedicalRecordCode);

                            $scope.messageData = initMessages(messageData);

                            if (isFirstCount) {
                                $timeout(function () {
                                    $.each($scope.messageData, function (index, item) {
                                        if (item.menuClass == '系统公告') {
                                            var filterRead = _.filter(item.messageItems, { hasRead: false });
                                            messageFilterReadCnt += filterRead.length;
                                        }
                                        else {
                                            messageFilterReadCnt += item.count;
                                        }
                                    });
                                }, 1 * 1000);
                                isFirstCount = false;
                            } else {
                                //刷新提醒数字
                                $scope.$broadcast('to-child-messages-count', getMessageCount());
                            }

                            messageCenterSvc.getHideTimeOutSeconds().success(function (seconds) {
                                $timeout(function () {
                                    $.each($scope.messageData, function (index, item) {
                                        var time;
                                        if (item) {
                                            time = item.createTimeText;
                                        }
                                        else {
                                            time = toLongDateTimeString(new Date());
                                        }

                                        if (item.menuClass == '库存预警' || item.menuClass == '短信预警') {
                                            item.isShow = false;
                                            $scope.bizMessageCodes.push({ code: keys.RemindTimeOutCode, time: time });
                                            saveBizMessageCodes($scope.bizMessageCodes);
                                        }
                                    });
                                }, seconds * 1000);
                            });
                        });
                    };

                    var removeMessage = function (messageId) {
                        var remainedMessages = _.reject($scope.messageData, { id: messageId });
                    };

                    var onAppInitialized = function () {
                        $timeout(initView, 200);
                    };

                    var loginSCRM = function () {
                        window.open("/Scrm");
                    };

                    var readMessage = function (id) {
                        userSvc.readMessage(id).success(function (fullMessageData) {
                            loadMessages();
                            var modalInstance = $modal.open({
                                animation: true,
                                backdrop: 'static',
                                template: '<message-detail-view></message-detail-view>',
                                controller: 'MessageDetailCtrl',
                                windowClass: 'message-detail-dialog',
                                size: 'lg',
                                resolve: {
                                    host: function () {
                                        if (messageFilterReadCnt) {
                                            messageFilterReadCnt = messageFilterReadCnt - 1;
                                            $scope.$broadcast('to-child-messages-count', messageFilterReadCnt);
                                        }
                                        return {
                                            message: fullMessageData
                                        };
                                    }
                                }
                            });
                        });

                    };

                    var getUnReadCount = function (message) {
                        var columns = _.filter(message.messageItems, { hasRead: false });

                        if (message.menuBigClass == '系统公告') {
                            return columns.length;
                        }
                        else {
                            return message.count;
                        }
                    }

                    var getMessageCount = function () {
                        var messageCnt = 0;
                        var messageFilterReadCnt = 0;
                        if ($scope.messageData) {
                            $.each($scope.messageData, function (index, item) {
                                messageCnt += item.count;

                                if (item.menuClass == '系统公告') {
                                    var filterRead = _.filter(item.messageItems, { hasRead: false });
                                    messageFilterReadCnt += filterRead.length;
                                }
                                else {
                                    messageFilterReadCnt += item.count;
                                }
                            })
                        }
                        return messageFilterReadCnt;
                    };

                    var reLoadMessage = function () {
                        var permissionCodes = new Array();
                        if (permissionProvider.isAllowed(keys.weChatBizMessageCode)) {
                            permissionCodes.push(keys.weChatBizMessageCode);
                        }
                        else if (loginContext.dashboardType) {
                            permissionCodes.push(keys.weChatBizMessageCode);
                        }
                        messageCenterSvc.getMessages(permissionCodes).success(function (messages) {
                            $scope.messageData = initMessages(messages);
                        });
                    };

                    var openPointBoard = function (eventElement) {
                        $scope.isPointBoardOpened = true;
                        globalEventHandler.onMousedown(onGlobalMouseDownHandler);
                        globalEventHandler.onMouseenter(onGlobalMouseEnterHandler)
                        Ares.sensors.track('AppSideBarOperation', {
                            'OperationType': '积分',
                        });
                    };

                    var onGlobalMouseDownHandler = function (event) {
                        var isOnPopover = $(event.target).parents('.popover').length;
                        if (!isOnPopover) {
                            $scope.$apply(function () {
                                closePointBoard();
                            });
                        }
                    };

                    var onGlobalMouseEnterHandler = function (event) {
                        var isOnPopover = $(event.target).parents('.popover').length;
                        if (!isOnPopover) {
                            $scope.$apply(function () {
                                closePointBoard();
                            });
                        } else {
                            openPointBoard(event);
                        }
                    };

                    var closePointBoard = function () {
                        $scope.isPointBoardOpened = false;
                        globalEventHandler.offMousedown();
                    };

                    var onMouseLeave = function (event) {
                        if (!$(event.toElement).hasClass('popover')) {
                            closePointBoard();
                        }
                    };

                    var createPatient = function () {
                        if (loginContext.isAdminOffice) {
                            patientUtil.createAdminPatient(true).then(function (newPatientData) {
                                appNav.goToPatient(newPatientData.id);
                            });
                        } else {
                            patientUtil.createPatient(true).then(function (newPatientData) {
                                if (loginContext.isGroup) {
                                    var permissionLevel = patientUtil.getPatientPermissionLevel();
                                    if (permissionLevel == enums.PatientPermissionLevel.Personal) {
                                        if ((!newPatientData.extension && loginContext.providerId) || loginContext.providerId != newPatientData.extension.onlineConsultantId) {
                                            aresDialog.info('提示', '无患者数据访问权限！');
                                            return;
                                        }
                                    }
                                }
                                appNav.goToPatient(newPatientData.id);
                            });
                        }
                    };

                    var saveBizMessageCodes = function (value) {
                        bizMessageCodeCache.saveObject(value);
                    };

                    var init = function () {
                        initMessage();
                    };

                    var initEnableFaceRecognition = function () {
                        officeOptionSvc.getOfficeOption(officeOptionSvc.optionKeys.IsFaceRecognitionEnabled).then(function (isEnable) {
                            $scope.isFaceRecognitionEnabled = isEnable;
                        });
                    };

                    var initEnableReadCard = function () {
                        $scope.isEnableICCard = 1;
                        officeOptionSvc.getOfficeOption(officeOptionSvc.optionKeys.IsEnableICCard).then(function (isEnable) {
                            $scope.isEnableICCard = isEnable;
                        });
                    };

                    var initYibaoGatewayInfo = function () {
                        $scope.isYibaoReadCardEnabled = false; // init
                        var isYibaoGatewayEnabledQuery = officeOptionSvc.getOfficeOption(officeOptionSvc.optionKeys.IsYibaoGatewayEnabled).then(function (isEnable) {
                            $scope.isYibaoGatewayEnabled = isEnable;
                            if (!isEnable) return;
                            if (!dataDicSvc.insuranceMateDataDic) {
                                dataDicSvc.initialize();
                            }
                            dataDicSvc.insuranceMateDataDic.load().then(function (x) {
                                if (!x || x.length == 0) return;
                                $scope.yibaoChannelDict = x.map(function (y) {
                                    return { name: y.displayName, value: y.name, canReadCard: y.canReadCard };
                                });
                                if ($scope.yibaoChannelDict.length >= 1) {
                                    $scope.yibaoUseChannel = $scope.yibaoChannelDict[0].value;
                                    $scope.yibaoUseChannelCache = sessionCache.getCache(sessionCache.keys.YibaoUseChannel);
                                    $scope.yibaoUseChannelCache.saveValue($scope.yibaoUseChannel);

                                    // set field isYibaoReadCardEnabled
                                    if ($scope.yibaoChannelDict[0].canReadCard === true) {
                                        $scope.isYibaoReadCardEnabled = true;
                                    }
                                }
                            });
                        });

                        hebePortal.register('ares.business.yibaoUseChannel', function (data, uniqId) {
                            hebePortal.post('hebe.business.yibaoUseChannel', {
                                yibaoUseChannel: $scope.yibaoUseChannelCache.loadValue(),
                            }, uniqId);
                        });

                        return isYibaoGatewayEnabledQuery;
                    };

                    var onSelectYibaoChannel = function (yibaoUseChannel) {
                        $scope.yibaoUseChannel = yibaoUseChannel;
                        $scope.yibaoUseChannelCache.saveValue($scope.yibaoUseChannel);
                        if ($scope.yibaoChannelDict.find(keyValue => keyValue.value === yibaoUseChannel).canReadCard) {
                            $scope.isYibaoReadCardEnabled = true;
                        } else {
                            $scope.isYibaoReadCardEnabled = false;
                        }
                    };

                    var initMessageConfig = function () {
                        officeOptionSvc.getOfficeOptions([
                            officeOptionSvc.optionKeys.IsMessageNotDisturbDisalbed,
                            officeOptionSvc.optionKeys.IsMessageClearAllDisalbed,
                            officeOptionSvc.optionKeys.MessagePostponeConfig,
                            officeOptionSvc.optionKeys.IsStrongMessageDisabled,
                            officeOptionSvc.optionKeys.EnabledApptChannel,
                            officeOptionSvc.optionKeys.IsYibaoGatewayEnabled,
                        ]).then(function (result) {
                            if (_.isArray(result)) {
                                $scope.isMessageNotDisturbDisalbed = !!result[0];
                                $scope.isMessageClearAllDisalbed = !!result[1];
                                $scope.isApptApplyDisabled = result[2] ? !!result[2].IsApptApplyDisabled : false;
                                $scope.isStrongMessageDisabled = !!result[3];
                                $scope.enabledApptChannel = result[4];
                                $scope.isYibaoGatewayEnabled = result[5];
                            } else {
                                $scope.isMessageNotDisturbDisalbed = false;
                                $scope.isMessageClearAllDisalbed = false;
                                $scope.isApptApplyDisabled = false;
                                $scope.isStrongMessageDisabled = false;
                                $scope.enabledApptChannel = '';
                                $scope.isYibaoGatewayEnabled = false;
                            }
                        });
                    };

                    var readCard = function () {
                        cardReaderService.read()
                            .then(function (result) {
                                var card = result.data;
                                if (card && card.issuccess && card.cardno) {
                                    var cardNo = card.cardno;
                                    var input = element.find('#search-input-box');
                                    input.val(cardNo);
                                    input.click();
                                } else {
                                    aresNotification.error('读卡失败，请检查卡片是否正确插入或重试');
                                }
                            })
                            .catch(function (error) {
                                aresNotification.error('读卡失败，请检查本地服务是否正常运行');
                            });
                    };

                    var onWebchatClick = function () {
                        var userId = loginContext.userId;
                        customerServiceSvc.update(userId);
                        qimoChatClick();
                        addSensorTrack('客服');
                    };

                    var initCustomizeSetting = function () {
                        tenantSvc.GetTenantIsCustomizeOpen().then(function (isCustomizeOpen) {
                            $scope.isCustomizeOpen = isCustomizeOpen.data;
                            tenantSvc.getTenantOptionExtension().then(function (extension) {
                                $scope.extension = extension.data;
                            });
                        });
                    };

                    var isShowMessage = function (messageData) {
                        return messageData
                            && messageData.length > 0
                            && _.any(messageData, function (message) {
                                return message.isShow && getUnReadCount(message) > 0;
                            });
                    };

                    var goToCredits = function () {
                        appNav.goToOfficeCredits();
                    };

                    var isShowPointLinkPermission = function () {
                        permissionProvider.loadPermissions().then(function () {
                            if (permissionProvider.isAllowed('tenantSettings.account')) {
                                $scope.isShowPointLink = true;
                            }
                        })
                    };
                    var recognitionFaceInfo = function () {
                        $timeout(function () {
                            var modalInstance = $modal.open({
                                animation: true,
                                backdrop: 'static',
                                template: '<face-recognition-view></face-recognition-view>',
                                controller: 'FaceRecognitionCtrl',
                                size: 'md',
                                resolve: {
                                    host: function () {
                                        return {
                                        };
                                    }
                                }
                            });
                        })
                    };
                    var readIdentityInfo = function () {
                        localSvc.readIdentityInfo().then(function (result) {
                            if (result && result.issuccess) {
                                var patientIdentityInfo = result.data;
                                var idcardNumber = patientIdentityInfo.idcardNumber
                                var input = element.find('#search-input-box');
                                input.val(idcardNumber);
                                input.click();
                            } else {
                                var errorTitle = "提示";
                                var errorMsg = "身份证读取失败，请检查身份证读取工具是否正常运行。";
                                if (result && !result.issuccess && result.msg) {
                                    errorMsg = result.msg;
                                }
                                aresDialog.warn(errorTitle, errorMsg);
                            }
                        }, function () {
                            var errorTitle = "提示";
                            var errorMsg = "身份证读取失败，请检查身份证读取工具是否正常运行。";
                            aresDialog.warn(errorTitle, errorMsg);
                        });
                    };

                    var readLcCrmEnabled = function () {
                        systemConfigSvc.getIsLcCrmEnabled().then(function (isLcCrmEnabled) {
                            $scope.isLcCrmEnabled = isLcCrmEnabled;
                        });
                    };

                    var editMemoClick = function () {
                        $timeout(function () {
                            var $modalInstance = $modal.open({
                                animation: true,
                                backdrop: 'static',
                                template: '<memo-edit-view></memo-edit-view>',
                                controller: 'MemoEditCtrl',
                                backdropClass: 'ares-modal-backdrop',
                                resolve: {
                                    host: function () {
                                        return {
                                            type: "add"
                                        };
                                    }
                                }
                            });
                        })
                    };

                    var memoCenterClick = function () {
                        $timeout(function () {
                            var $modalInstance = $modal.open({
                                animation: true,
                                backdrop: 'static',
                                template: '<memo-center-view></memo-center-view>',
                                controller: 'MemoCenterCtrl',
                                backdropClass: 'ares-modal-backdrop'
                            });
                        })
                        addSensorTrack('备忘');
                    };

                    var memoCenterClick = function () {
                        var $modalInstance = aresModalShelf.open({
                            template: '<memo-center-view></memo-center-view>',
                            controller: 'MemoCenterCtrl',
                            title: '备忘中心',
                            titleIconClass: 'iconfont icon-beiwanglu',
                            needActive: true
                        });
                        addSensorTrack('备忘');
                    };

                    var addSensorTrack = function (eventType) {
                        Ares.sensors.track('AppTopBarEvent', {
                            'EventType': eventType
                        });
                    };

                    var goToEnterpriseCenter = function () {
                        Ares.sensors.track('ClinicCenter', {
                            'OperationType': '诊所概览入口',
                        });
                        // appNav.goToEnterpriseCenter();
                    };
                    var isShowPatientSearch = function () {
                        permissionProvider.loadPermissions().then(function () {
                            if (permissionProvider.isAllowed('patientMgmt.globalSearch')) {
                                $scope.showPatientSearch = true;
                            }
                            if (permissionProvider.isAllowed('patientMgmt.create')) {
                                $scope.showPatientCreate = true;
                            }
                        })
                    };

                    var initDraggableBox = function () {
                        $scope.isShowAppt = false;
                        var draggableEl = element.find("#J_topbar-draggable-box");
                        var timer = setInterval(function () {
                            if (draggableEl.draggable) {
                                clearInterval(timer);
                                draggableEl.draggable({
                                    handle: ".draggable-logo",
                                    start: function (event, ui) {
                                        Ares.sensors.track('webclick', {
                                            'OperationType': '拖动网络预约列表',
                                            'EventType': '网络预约操作'
                                        });
                                    }
                                });
                                return;
                            }
                        }, 200);


                    };

                    $scope.draggableToggle = function (action) {
                        $scope.isShowAppt = action === 'on';

                        if (action === 'on') {
                            Ares.sensors.track('webclick', {
                                'OperationType': '展开网络预约列表',
                                'EventType': '网络预约操作'
                            });
                        } else {
                            Ares.sensors.track('webclick', {
                                'OperationType': '折叠网络预约列表',
                                'EventType': '网络预约操作'
                            });
                        }
                    };

                    /**
                     * 检查口腔软件是否过期
                     */
                    var checkExpiration = function () {
                        var expiredDate = loginContext.expiredDate;
                        if (!expiredDate) return;
                        var dayDiff = moment(expiredDate).diff(moment().startOf('d'), 'd');
                        if (dayDiff < 31 && dayDiff >= 0) {
                            $scope.showExpiredHint = true;
                            $scope.expiredDate = moment(expiredDate).format('YYYY-MM-DD');
                        } else if (dayDiff < 0) {
                            var deadlineDate = moment(expiredDate).add(1, 'M');
                            // 最终日期后不再提示
                            if (moment().isBefore(deadlineDate)) {
                                openExpiredModal();
                            }
                        }

                    };

                    var hideExpiredHint = function () {
                        $scope.showExpiredHint = false;
                    };

                    var hideUpgradeHint = function () {
                        $scope.showUpgradeHint = false;
                    };

                    var hideUpgradeHintForever = function () {
                        $scope.showUpgradeHint = false;
                        localStorage.setItem('topbar_hideUpgradeHint', '1');
                    };

                    var openExpiredModal = function () {
                        $modal.open({
                            title: '续费',
                            template: '<saas-expired-modal-view></saas-expired-modal-view>',
                            windowClass: 'saas-expired-modal-window',
                            controller: 'SaasExpiredModalCtrl',
                            backdropClass: 'saas-expired-modal-backdrop',
                            backdrop: 'static',
                        })
                    };

                    var openBmsSaasModal = function (title) {
                        hideExpiredHint();
                        hideUpgradeHint();
                        aresModalShelf.open({
                            template: '<bms-product-modal-view application-code="\'saas\'" action="1" channel="\'企业中心\'"></bms-product-modal-view>',
                            title: title,
                            needActive: true,
                            customWidth: '1180px'
                        });
                    };

                    var goToBmsEnterpriseSoftware = function () {
                        appNav.goToEnterpriseApplications();
                    };

                    var subSidebarEvent = function () {
                        eventAggregator.subscribe($scope, eventAggregator.events.sidebarSubMenuToggle, function (event, data) {
                            if (data && data.subMenuVisible) {
                                $('#ares3-top-bar').css({ 'left': '200px' });
                            } else {
                                $('#ares3-top-bar').css({ 'left': '80px' });
                            }
                        });
                    };

                    var getCustomerConsultant = function () {
                        officeUtil.getCustomerSuccessConsutant().then(function (successConsutant) {
                            $scope.successConsutant = successConsutant;
                        });
                    };

                    var readYibaoCard = function () {
                        aresYibaoLocalUtil.readCard();
                    };

                    var getNPSConfig = function () {
                        $scope.npsResearch = {};
                        var defered = $q.defer();
                        systemMessageSvc.getNPSResearchConfig().success(function (npsConfig) {
                            $scope.isShowNpsResearch = (npsConfig != null);

                            if ($scope.isShowNpsResearch) {
                                $scope.npsResearch = npsConfig;
                            }

                            defered.resolve();
                        });

                        return defered.promise;
                    };

                    var npsResearchClick = function () {
                        if ($scope.isNpsResearchOpened) {
                            $scope.modalInstance.close();
                        }

                        var extraData = {};

                        try {

                            if ($scope.npsResearch.extraData) {
                                extraData = eval("(" + $scope.npsResearch.extraData + ")");
                            }
                        }
                        catch (exception) {
                            extraData = {};
                        }
                        var height = document.documentElement.clientHeight - 100;
                        var modalConfig =
                        {
                            title: '满意度小调查',
                            template: '<div style=\'width:100%; height:auto\'><iframe src=' + $scope.npsResearch.extraLink + ' style=\'width:100%; height:' + height + 'px\'></iframe></div>',
                            controller: function () { }
                        };

                        if (extraData.showWindowWidth) {
                            modalConfig['customWidth'] = extraData.showWindowWidth + 'px';
                        }

                        $scope.modalInstance = aresModalShelf.open(modalConfig);

                        $scope.isNpsResearchOpened = true;

                        //addSensorTrack('');
                    };

                    var getAcceptanceReport = function () {
                        $scope.allowedToAcceptance = permissionProvider.isAllowed('setting.accountAcceptance');

                        if (!$scope.showExpiredHint) {
                            $scope.showAcceptanceReportHint = false;
                            practiceSvc.getFullOffice(loginContext.officeId).then(function (office) {
                                $scope.officeInfo = office.data;
                                // 诊所没有过期期限，不显示验收提醒
                                if (!$scope.officeInfo.expiredDate) {
                                    return;
                                }
                                $scope.officeOpenDate = moment(office.data.recordCreatedTime).format('YYYY-MM-DD');
                                var crDate = moment(office.data.recordCreatedTime).add(-1, 'days').format('YYYY-MM-DD');
                                var today = moment(Ares.today()).format('YYYY-MM-DD');
                                const dateDiffDays = moment(today).diff(moment(crDate), 'day');
                                if (dateDiffDays >= 10 && dateDiffDays <= 15) {
                                    officeSvc.getAcceptanceReportByOfficeId(loginContext.officeId).then(function (report) {
                                        $scope.showAcceptanceReportHint = true;
                                        if (report.data) {
                                            $scope.showAcceptanceReportHint = !report.data.isAccepted;
                                            $scope.acceptanceReport = report.data;
                                        }
                                    });
                                }
                            });
                        }
                    };

                    var acceptanceDialog = function () {
                        moduleUtil.load('tenant').then(function () {
                            var tenantUtil = $injector.get('tenantUtil');
                            return tenantUtil.openAcceptanceReportDialog($scope.officeInfo).then(function (result) {

                            });
                        });
                    };

                    var hideAcceptanceReportHint = function () {
                        $scope.showAcceptanceReportHint = false;
                    };

                    (function initialize() {
                        $scope.isShowStrongMessage = false;
                        $scope.isStrongMessageDisabled = false;
                        $scope.isShowMoreMessage = false;
                        $scope.enabledApptChannel = '';
                        $scope.readIdentityInfo = readIdentityInfo;
                        $scope.popoverPlacement = $scope.popoverPlacement || 'bottom';
                        $scope.pointBoardUrl = 'pointBoard.html';
                        $scope.isPointBoardOpened = false;
                        $scope.bizMessageCodes = [];
                        $scope.apptApplysRemind = {};
                        $scope.checkoutRemind = [];
                        $scope.applyRemind = [];
                        $scope.linkHelpPage = linkHelpPage;
                        $scope.refreshView = refreshView;
                        $scope.enableScrm = false;
                        $scope.hideThis = hideThis;
                        $scope.goToNavigate = goToNavigate;
                        $scope.removeMessage = removeMessage;
                        $scope.loginSCRM = loginSCRM;
                        $scope.readMessage = readMessage;
                        $scope.getUnReadCount = getUnReadCount;
                        $scope.openPointBoard = openPointBoard;
                        $scope.closePointBoard = closePointBoard;
                        $scope.onMouseLeave = onMouseLeave;
                        $scope.createPatient = createPatient;
                        $scope.isAdminOffice = loginContext.isAdminOffice;
                        $scope.isGroup = loginContext.isGroup;
                        $scope.readCard = readCard;
                        $scope.onWebchatClick = onWebchatClick;
                        $scope.isShowMessage = isShowMessage;
                        $scope.goToCredits = goToCredits;
                        $scope.recognitionFaceInfo = recognitionFaceInfo;
                        $scope.editMemoClick = editMemoClick;
                        $scope.memoCenterClick = memoCenterClick;
                        $scope.goToEnterpriseCenter = goToEnterpriseCenter;
                        $scope.goToApptApply = goToApptApply;
                        $scope.hideExpiredHint = hideExpiredHint;
                        $scope.hideUpgradeHint = hideUpgradeHint;
                        $scope.hideUpgradeHintForever = hideUpgradeHintForever;
                        $scope.openBmsSaasModal = openBmsSaasModal;
                        $scope.goToBmsEnterpriseSoftware = goToBmsEnterpriseSoftware;
                        $scope.showUpgradeHint = loginContext.officeEdition === 'Edition.Basic40' && localStorage.getItem('topbar_hideUpgradeHint') !== '1';
                        $scope.readYibaoCard = readYibaoCard;
                        $scope.onSelectYibaoChannel = onSelectYibaoChannel;
                        initEnableReadCard();
                        readLcCrmEnabled();
                        initMessageConfig();
                        initYibaoGatewayInfo();
                        officeOptionUtil.setIsReadIdentityCardEnabled($scope);
                        initEnableFaceRecognition();
                        initCustomizeSetting();
                        isShowPointLinkPermission();
                        $scope.npsResearchClick = npsResearchClick;
                        $scope.acceptanceDialog = acceptanceDialog;
                        $scope.hideAcceptanceReportHint = hideAcceptanceReportHint;
                        $scope.allowedToAcceptance = false;
                        //subscribeEvents();
                        if ($rootScope.isInitialized) {
                            $timeout(initView, 200);
                        } else {
                            eventAggregator.subscribe($scope, 'appInitialized', onAppInitialized);
                        }
                        $scope.$on('$destroy', function () {
                            globalEventHandler.dispose();
                        });
                        if (!$scope.isAdminOffice) {
                            // Delay 3s to load message
                            $timeout(init, 5000);
                        }
                        element.on('input', '#search-input-box', function (e) {
                            $scope.patientValue = e.target.value;

                        });
                        element.on('click', '#topClose', function (event) {
                            $scope.patientValue = '';
                        });
                        $timeout(isShowPatientSearch, 1000);
                        //$scope.test = onSpeeechCallReceived;

                        initDraggableBox();
                        checkExpiration();
                        subSidebarEvent();

                        getCustomerConsultant();

                        getNPSConfig();

                        getAcceptanceReport();
                    }());
                }
            }
        }]);

var marketingManagement;
(function (marketingManagement) {
    var Ares3MarketingManagementAppointmentChannelPage = /** @class */ (function () {
        function Ares3MarketingManagementAppointmentChannelPage(appNav, dataDicSvc) {
            var _this = this;
            this.appNav = appNav;
            this.dataDicSvc = dataDicSvc;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\">\n                <ares-tab states=\"states\" ng-if=\"initialized && canConfigApptInventory()\"></ares-tab>\n                <div ng-if=\"initialized && !canConfigApptInventory()\">\n                    <h3>\u60A8\u5C1A\u672A\u5F00\u901A\u7B2C\u4E09\u65B9\u6E20\u9053\u9884\u7EA6\uFF0C\u5982\u6709\u9700\u8981\uFF0C\u8BF7\u8054\u7CFB\u9886\u5065\u5BA2\u670D\u3002</h3>\n                </div>\n            </div>\n        ";
            this.link = function ($scope) {
                var TabItem = _this.appNav.TabItem;
                _this.dataDicSvc.enabledChannelsDic.load().then(function (channels) {
                    $scope.enabledChannels = channels;
                    $scope.states = [
                        new TabItem('marketingManagement.appointmentChannel.mapping', '渠道服务项目映射', '', null),
                        new TabItem('marketingManagement.appointmentChannel.baseSetting', '渠道基础配置', '', null),
                        new TabItem('marketingManagement.appointmentChannel.inventorySetting', '渠道库存配置', '', null),
                    ];
                    $scope.initialized = true;
                });
                $scope.canConfigApptInventory = function () {
                    return $scope.enabledChannels && $scope.enabledChannels.length > 0;
                };
            };
        }
        Ares3MarketingManagementAppointmentChannelPage.$inject = ['appNav', 'dataDicSvc'];
        return Ares3MarketingManagementAppointmentChannelPage;
    }());
    marketingManagementModule.directive('ares3MarketingManagementAppointmentChannelPage', Ares.tsDirective(Ares3MarketingManagementAppointmentChannelPage));
})(marketingManagement || (marketingManagement = {}));

var marketingManagement;
(function (marketingManagement) {
    var Ares3MarketingManagementGiftCardPage = /** @class */ (function () {
        function Ares3MarketingManagementGiftCardPage(appNav, systemConfigUtil) {
            var _this = this;
            this.appNav = appNav;
            this.systemConfigUtil = systemConfigUtil;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\">\n                <ares-tab states=\"states\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope) {
                var TabItem = _this.appNav.TabItem;
                _this.systemConfigUtil.getConfigValue(_this.systemConfigUtil.configKeys.IsEnableGiftCard).then(function (isShowGiftCard) {
                    var states = [
                        new TabItem('marketingManagement.giftCard.detail', '卡券领用明细', '', 'membership.cardDetail'),
                        new TabItem('marketingManagement.giftCard.discount', '营销优惠管理', '', 'membership.discount|membership.publish'),
                    ];
                    if (isShowGiftCard) {
                        states.push(new TabItem('marketingManagement.giftCard.bearer', '不记名卡管理', '', 'membership.giftCard'));
                    }
                    $scope.states = states;
                });
            };
        }
        Ares3MarketingManagementGiftCardPage.$inject = ['appNav', 'systemConfigUtil'];
        return Ares3MarketingManagementGiftCardPage;
    }());
    marketingManagementModule.directive('ares3MarketingManagementGiftCardPage', Ares.tsDirective(Ares3MarketingManagementGiftCardPage));
})(marketingManagement || (marketingManagement = {}));

var marketingManagement;
(function (marketingManagement) {
    var Ares3MarketingManagementMemberPage = /** @class */ (function () {
        function Ares3MarketingManagementMemberPage(appNav, moduleOptionProvider) {
            var _this = this;
            this.appNav = appNav;
            this.moduleOptionProvider = moduleOptionProvider;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\">\n                <ares-tab states=\"states\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope) {
                var TabItem = _this.appNav.TabItem;
                var states = [
                    new TabItem('marketingManagement.member.list', '会员列表', '', 'membership.list'),
                ];
                if (_this.moduleOptionProvider.isMembershipUpgradeEnabled()) {
                    states.push(new TabItem('marketingManagement.member.levelApply', '会员等级申请', '', 'membership.typeApply'));
                }
                states.push(new TabItem('marketingManagement.member.changeLog', '会员变动记录', '', 'membership.list'));
                states.push(new TabItem('marketingManagement.member.transactionDetail', '储值卡交易明细', '', 'membership.transaction'));
                $scope.states = states;
            };
        }
        Ares3MarketingManagementMemberPage.$inject = ['appNav', 'moduleOptionProvider'];
        return Ares3MarketingManagementMemberPage;
    }());
    marketingManagementModule.directive('ares3MarketingManagementMemberPage', Ares.tsDirective(Ares3MarketingManagementMemberPage));
})(marketingManagement || (marketingManagement = {}));

var marketingManagement;
(function (marketingManagement) {
    var Ares3MarketingManagementReferralDetailPage = /** @class */ (function () {
        function Ares3MarketingManagementReferralDetailPage(appNav, loginContext) {
            var _this = this;
            this.appNav = appNav;
            this.loginContext = loginContext;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\">\n                <ares-tab states=\"states\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope) {
                var TabItem = _this.appNav.TabItem;
                $scope.states = [
                    new TabItem('marketingManagement.referralDetail.referer', '推荐人明细', '', null),
                    new TabItem('marketingManagement.referralDetail.referee', '被推荐人明细', '', null),
                ];
            };
        }
        Ares3MarketingManagementReferralDetailPage.$inject = ['appNav', 'loginContext'];
        return Ares3MarketingManagementReferralDetailPage;
    }());
    marketingManagementModule.directive('ares3MarketingManagementReferralDetailPage', Ares.tsDirective(Ares3MarketingManagementReferralDetailPage));
})(marketingManagement || (marketingManagement = {}));

var marketingManagement;
(function (marketingManagement) {
    var Ares3MarketingManagementReferralRewardPage = /** @class */ (function () {
        function Ares3MarketingManagementReferralRewardPage(appNav, loginContext) {
            var _this = this;
            this.appNav = appNav;
            this.loginContext = loginContext;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\">\n                <ares-tab states=\"states\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope) {
                var TabItem = _this.appNav.TabItem;
                $scope.states = [
                    new TabItem('marketingManagement.referralReward.arrival', '到店激励明细', '', null),
                    new TabItem('marketingManagement.referralReward.consumption', '单笔消费激励明细', '', null),
                    new TabItem('marketingManagement.referralReward.consumptionSum', '累计消费激励明细', '', null),
                ];
            };
        }
        Ares3MarketingManagementReferralRewardPage.$inject = ['appNav', 'loginContext'];
        return Ares3MarketingManagementReferralRewardPage;
    }());
    marketingManagementModule.directive('ares3MarketingManagementReferralRewardPage', Ares.tsDirective(Ares3MarketingManagementReferralRewardPage));
})(marketingManagement || (marketingManagement = {}));

var marketingManagement;
(function (marketingManagement) {
    var Ares3MarketingManagementReferralSummaryPage = /** @class */ (function () {
        function Ares3MarketingManagementReferralSummaryPage(appNav, loginContext, aresModalShelf, moduleOptionProvider) {
            var _this = this;
            this.appNav = appNav;
            this.loginContext = loginContext;
            this.aresModalShelf = aresModalShelf;
            this.moduleOptionProvider = moduleOptionProvider;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\">\n                <ares-tab states=\"states\" commands=\"commands\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope) {
                var TabItem = _this.appNav.TabItem;
                $scope.states = [new TabItem('marketingManagement.referralSummary.dashboard', '概览', '', null)];
                var toggleSettingSlide = function () {
                    var tabs = [{
                            title: '到店激励',
                            template: '<referral-arrival-config-view></referral-arrival-config-view>',
                            setDefault: true
                        }];
                    if (_this.moduleOptionProvider.isReferralPaymentRuleEnabled()) {
                        tabs.push({
                            title: '单笔消费激励',
                            template: '<referral-payment-config-view></referral-payment-config-view>'
                        });
                        tabs.push({
                            title: '累计消费激励',
                            template: '<referral-total-payment-config-view></referral-total-payment-config-view>'
                        });
                    }
                    var shelfInstance = _this.aresModalShelf.open({ tabs: tabs, customWidth: '1200px' });
                };
                var commandOption = { permissionCode: 'referralCenter.referralConfig' };
                // @ts-ignore
                $scope.commands = [new Ares.TabCommand('设置', toggleSettingSlide, 'lc-btn lc-btn-primary', 0, commandOption)];
            };
        }
        Ares3MarketingManagementReferralSummaryPage.$inject = ['appNav', 'loginContext', 'aresModalShelf', 'moduleOptionProvider'];
        return Ares3MarketingManagementReferralSummaryPage;
    }());
    marketingManagementModule.directive('ares3MarketingManagementReferralSummaryPage', Ares.tsDirective(Ares3MarketingManagementReferralSummaryPage));
})(marketingManagement || (marketingManagement = {}));

/**
 * 把hebe页面简单地包一层，用作tab下的ui-view
 */
var medicalService;
(function (medicalService) {
    'use strict';
    var Ares3PatientVideoListView = /** @class */ (function () {
        function Ares3PatientVideoListView() {
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-patient-video-list\" style=\"width: 100%; height: 100%;\">\n                <ares-new-home-view target-route=\"managementCenter.patientVideo\"></ares-new-home-view>\n            </div>\n        ";
        }
        Ares3PatientVideoListView.$inject = [];
        return Ares3PatientVideoListView;
    }());
    dentalLabModule.directive('ares3PatientVideoListView', Ares.tsDirective(Ares3PatientVideoListView));
})(medicalService || (medicalService = {}));

var medicalService;
(function (medicalService) {
    var Ares3PatientVideoPage = /** @class */ (function () {
        function Ares3PatientVideoPage(appNav) {
            var _this = this;
            this.appNav = appNav;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-patient-video-page\">\n                <style>\n                    .ares3-patient-video-page {\n                        width: 100%;\n                        height: 100%;\n                    }\n                    .ares3-patient-video-page div[ui-view] {\n                        width: 100%;\n                        height: calc(100% - 52px);\n                    }\n                </style>\n                <ares-tab states=\"states\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope) {
                var TabItem = _this.appNav.TabItem;
                $scope.states = [
                    new TabItem('medicalService.patientVideo.list', '医患沟通视频', '', 'pdCommunication.video'),
                ];
            };
        }
        Ares3PatientVideoPage.$inject = ['appNav'];
        return Ares3PatientVideoPage;
    }());
    medicalServiceModule.directive('ares3PatientVideoPage', Ares.tsDirective(Ares3PatientVideoPage));
})(medicalService || (medicalService = {}));

var officeManagement;
(function (officeManagement) {
    var Ares3OfficeManagementExportPage = /** @class */ (function () {
        function Ares3OfficeManagementExportPage(appNav, moduleOptionProvider) {
            var _this = this;
            this.appNav = appNav;
            this.moduleOptionProvider = moduleOptionProvider;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\">\n                <ares-tab states=\"states\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope) {
                var TabItem = _this.appNav.TabItem;
                var states = [];
                if (_this.moduleOptionProvider.isHealthBureauDataExportEnabled()) {
                    states.push(new TabItem('officeManagement.export.dataDownload', '业务数据下载', '', 'dataExport.healthBureauDataExport'));
                }
                if (_this.moduleOptionProvider.isBizDataBackupEnabled()) {
                    states.push(new TabItem('officeManagement.export.dataBackup', '业务数据备份', '', "dataExport.bizDataBackup"));
                }
                if (_this.moduleOptionProvider.isHealthBureauDataExportEnabled_Shenzhen()) {
                    states.push(new TabItem('officeManagement.export.shenzhenUpload', '深圳机构数据上传', '', 'dataExport.healthBureauDataExport'));
                }
                $scope.states = states;
            };
        }
        Ares3OfficeManagementExportPage.$inject = ['appNav', 'moduleOptionProvider'];
        return Ares3OfficeManagementExportPage;
    }());
    officeManagementModule.directive('ares3OfficeManagementExportPage', Ares.tsDirective(Ares3OfficeManagementExportPage));
})(officeManagement || (officeManagement = {}));

var officeManagement;
(function (officeManagement) {
    var Ares3OfficeManagementOrgchainPage = /** @class */ (function () {
        function Ares3OfficeManagementOrgchainPage(appNav) {
            var _this = this;
            this.appNav = appNav;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\">\n                <ares-tab states=\"states\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope) {
                var TabItem = _this.appNav.TabItem;
                $scope.states = [
                    new TabItem('officeManagement.orgchain.offices', '门诊信息', '', 'tenantSettings.office'),
                    new TabItem('officeManagement.orgchain.baseData', '配置分发', '', 'organizationManagement.baseData'),
                    new TabItem('officeManagement.orgchain.businessData', '数据共享', '', 'organizationManagement.baseData'),
                ];
            };
        }
        Ares3OfficeManagementOrgchainPage.$inject = ['appNav'];
        return Ares3OfficeManagementOrgchainPage;
    }());
    officeManagementModule.directive('ares3OfficeManagementOrgchainPage', Ares.tsDirective(Ares3OfficeManagementOrgchainPage));
})(officeManagement || (officeManagement = {}));

var officeManagement;
(function (officeManagement) {
    var Ares3OfficeManagementSecurityAccountPage = /** @class */ (function () {
        function Ares3OfficeManagementSecurityAccountPage(appNav) {
            var _this = this;
            this.appNav = appNav;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\">\n                <ares-tab states=\"states\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope) {
                var TabItem = _this.appNav.TabItem;
                $scope.states = [
                    new TabItem('officeManagement.accountSecurity.list', '账号安全', '', 'security.loginLog'),
                ];
            };
        }
        Ares3OfficeManagementSecurityAccountPage.$inject = ['appNav'];
        return Ares3OfficeManagementSecurityAccountPage;
    }());
    officeManagementModule.directive('ares3OfficeManagementSecurityAccountPage', Ares.tsDirective(Ares3OfficeManagementSecurityAccountPage));
})(officeManagement || (officeManagement = {}));

var officeManagement;
(function (officeManagement) {
    var Ares3OfficeManagementSecurityDevicePage = /** @class */ (function () {
        function Ares3OfficeManagementSecurityDevicePage(appNav) {
            var _this = this;
            this.appNav = appNav;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\">\n                <ares-tab states=\"states\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope) {
                var TabItem = _this.appNav.TabItem;
                $scope.states = [
                    new TabItem('officeManagement.deviceSecurity.management', '设备管理', '', 'deviceSecurity.management'),
                    new TabItem('officeManagement.deviceSecurity.application', '设备审批', '', 'deviceSecurity.application'),
                ];
            };
        }
        Ares3OfficeManagementSecurityDevicePage.$inject = ['appNav'];
        return Ares3OfficeManagementSecurityDevicePage;
    }());
    officeManagementModule.directive('ares3OfficeManagementSecurityDevicePage', Ares.tsDirective(Ares3OfficeManagementSecurityDevicePage));
})(officeManagement || (officeManagement = {}));

var officeManagement;
(function (officeManagement) {
    var Ares3OfficeManagementSecurityOperationPage = /** @class */ (function () {
        function Ares3OfficeManagementSecurityOperationPage(appNav) {
            var _this = this;
            this.appNav = appNav;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\">\n                <ares-tab states=\"states\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope) {
                var TabItem = _this.appNav.TabItem;
                $scope.states = [
                    new TabItem('officeManagement.operationSecurity.log', '操作日志', '', 'security.operationLog'),
                ];
            };
        }
        Ares3OfficeManagementSecurityOperationPage.$inject = ['appNav'];
        return Ares3OfficeManagementSecurityOperationPage;
    }());
    officeManagementModule.directive('ares3OfficeManagementSecurityOperationPage', Ares.tsDirective(Ares3OfficeManagementSecurityOperationPage));
})(officeManagement || (officeManagement = {}));

var officeManagement;
(function (officeManagement) {
    var Ares3OfficeManagementSecurityPage = /** @class */ (function () {
        function Ares3OfficeManagementSecurityPage(appNav) {
            var _this = this;
            this.appNav = appNav;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\">\n                <ares-tab states=\"states\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope) {
                var TabItem = _this.appNav.TabItem;
                $scope.states = [
                    new TabItem('officeManagement.security.account', '账号安全', '', 'security.loginLog'),
                    new TabItem('officeManagement.security.data', '患者数据', '', 'security.operationLog'),
                    new TabItem('officeManagement.security.operationLog', '操作日志', '', 'security.dataSetting')
                ];
            };
        }
        Ares3OfficeManagementSecurityPage.$inject = ['appNav'];
        return Ares3OfficeManagementSecurityPage;
    }());
    officeManagementModule.directive('ares3OfficeManagementSecurityPage', Ares.tsDirective(Ares3OfficeManagementSecurityPage));
})(officeManagement || (officeManagement = {}));

var officeManagement;
(function (officeManagement) {
    var Ares3OfficeManagementSecurityPatientPage = /** @class */ (function () {
        function Ares3OfficeManagementSecurityPatientPage(appNav) {
            var _this = this;
            this.appNav = appNav;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\">\n                <ares-tab states=\"states\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope) {
                var TabItem = _this.appNav.TabItem;
                $scope.states = [
                    new TabItem('officeManagement.patientSecurity.data', '患者数据', '', 'security.dataSetting'),
                ];
            };
        }
        Ares3OfficeManagementSecurityPatientPage.$inject = ['appNav'];
        return Ares3OfficeManagementSecurityPatientPage;
    }());
    officeManagementModule.directive('ares3OfficeManagementSecurityPatientPage', Ares.tsDirective(Ares3OfficeManagementSecurityPatientPage));
})(officeManagement || (officeManagement = {}));

var officeManagement;
(function (officeManagement) {
    var Ares3OfficeManagementSmsPage = /** @class */ (function () {
        function Ares3OfficeManagementSmsPage(appNav, moduleOptionProvider) {
            var _this = this;
            this.appNav = appNav;
            this.moduleOptionProvider = moduleOptionProvider;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\">\n                <ares-tab states=\"states\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope) {
                var TabItem = _this.appNav.TabItem;
                var states = [
                    new TabItem('officeManagement.sms.dashboard', '短信一览', '', 'shortMessage.list'),
                    new TabItem('officeManagement.sms.history', '短信记录', '', 'shortMessage.history'),
                    new TabItem('officeManagement.sms.batch', '短信群发', '', 'shortMessage.batch'),
                    new TabItem('officeManagement.sms.reply', '短信回复', '', 'shortMessaage.reply'),
                    new TabItem('officeManagement.sms.charge', '短信充值', '', 'shortMessage.charge'),
                    new TabItem('officeManagement.sms.statistics', '短信统计', '', 'shortMessage.statistics'),
                    new TabItem('officeManagement.sms.autoRule', '短信自动发送', '', 'shortMessage.charge'),
                ];
                if (_this.moduleOptionProvider.isShortmessageTemplateEditEnabled()) {
                    states.push(new TabItem('officeManagement.sms.templateConfig', '短信模板管理', '', 'shortMessage.shortMessageTemplateConfig'));
                }
                $scope.states = states;
            };
        }
        Ares3OfficeManagementSmsPage.$inject = ['appNav', 'moduleOptionProvider'];
        return Ares3OfficeManagementSmsPage;
    }());
    officeManagementModule.directive('ares3OfficeManagementSmsPage', Ares.tsDirective(Ares3OfficeManagementSmsPage));
})(officeManagement || (officeManagement = {}));

var officeManagement;
(function (officeManagement) {
    var Ares3OfficeAccountAcceptancePage = /** @class */ (function () {
        function Ares3OfficeAccountAcceptancePage(appNav) {
            var _this = this;
            this.appNav = appNav;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\">\n                <ares-tab states=\"states\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope) {
                var TabItem = _this.appNav.TabItem;
                $scope.states = [new TabItem('officeManagement.accountAcceptance.setting', '账户验收', 'glyphicon glyphicon-home', 'setting.accountAcceptance')];
            };
        }
        Ares3OfficeAccountAcceptancePage.$inject = ['appNav'];
        return Ares3OfficeAccountAcceptancePage;
    }());
    officeManagementModule.directive('ares3OfficeAccountAcceptancePage', Ares.tsDirective(Ares3OfficeAccountAcceptancePage));
})(officeManagement || (officeManagement = {}));

var officeManagement;
(function (officeManagement) {
    'use strict';
    var Ares3OfficeEditCtrl = /** @class */ (function () {
        function Ares3OfficeEditCtrl($scope, hebePortal, $modalInstance) {
            var _this = this;
            this.$scope = $scope;
            this.hebePortal = hebePortal;
            this.$modalInstance = $modalInstance;
            $scope.init = function () {
                _this.hebePortal.registerOnce('ares.hebeModal.imReady', function (data, uniqId) {
                    _this.uniqId = uniqId;
                    _this.hebePortal.post('hebe.hebeModal.config', {
                        modalName: 'officeEdit',
                        uniqId: uniqId,
                        data: true
                    });
                });
                _this.listenOnceForCloseMessage();
            };
        }
        Ares3OfficeEditCtrl.prototype.listenOnceForCloseMessage = function () {
            var _this = this;
            this.hebePortal.registerOnce('ares.hebeModal.close', function (data, uniqId) {
                if (uniqId !== _this.uniqId) {
                    _this.listenOnceForCloseMessage();
                    return;
                }
                _this.$modalInstance.close(data);
            });
        };
        Ares3OfficeEditCtrl.$inject = ['$scope', 'hebePortal', '$modalInstance'];
        return Ares3OfficeEditCtrl;
    }());
    var Ares3OfficeEditPage = /** @class */ (function () {
        function Ares3OfficeEditPage() {
            this.restrict = 'E';
            this.replace = true;
            this.template = "<div style=\"width: 100%; height: 100%;\">\n                <ares-new-home-view target-route=\"modalEntry\"></ares-new-home-view>\n            </div>";
            this.link = function ($scope) {
                $scope.init();
            };
        }
        Ares3OfficeEditPage.$inject = [];
        return Ares3OfficeEditPage;
    }());
    officeManagementModule.controller('Ares3OfficeEditCtrl', Ares.tsController(Ares3OfficeEditCtrl));
    officeManagementModule.directive('ares3OfficeEditPage', Ares.tsDirective(Ares3OfficeEditPage));
})(officeManagement || (officeManagement = {}));

var officeManagement;
(function (officeManagement) {
    var Ares3OfficeExpendCenterPage = /** @class */ (function () {
        function Ares3OfficeExpendCenterPage(appNav, aresModalShelf) {
            this.appNav = appNav;
            this.aresModalShelf = aresModalShelf;
            this.restrict = 'E';
            this.replace = true;
            this.template = "<div style=\"width: 100%; height: 100%;\">\n                <ares-new-home-view target-route=\"systemSetting.office.expend-center\"></ares-new-home-view>\n            </div>";
            this.link = function ($scope) {
            };
        }
        Ares3OfficeExpendCenterPage.$inject = ['appNav', 'aresModalShelf'];
        return Ares3OfficeExpendCenterPage;
    }());
    officeManagementModule.directive('ares3OfficeExpendCenterPage', Ares.tsDirective(Ares3OfficeExpendCenterPage));
})(officeManagement || (officeManagement = {}));

var officeManagement;
(function (officeManagement) {
    var Ares3OfficeManagementAppointmentResourcePage = /** @class */ (function () {
        function Ares3OfficeManagementAppointmentResourcePage(appNav, aresModalShelf, moduleOptionProvider) {
            var _this = this;
            this.appNav = appNav;
            this.aresModalShelf = aresModalShelf;
            this.moduleOptionProvider = moduleOptionProvider;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\">\n                <ares-tab states=\"states\"  commands=\"commands\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope, element, attrs) {
                var TabItem = _this.appNav.TabItem;
                $scope.states = [
                    new TabItem('officeManagement.appointmentResource.rule', '号源规则配置', '', 'setting.providerResourceView'),
                    new TabItem('officeManagement.appointmentResource.view', '号源概览', '', 'setting.appointmentResourceView'),
                ];
            };
        }
        Ares3OfficeManagementAppointmentResourcePage.$inject = ['appNav', 'aresModalShelf', 'moduleOptionProvider'];
        return Ares3OfficeManagementAppointmentResourcePage;
    }());
    officeManagementModule.directive('ares3OfficeManagementAppointmentResourcePage', Ares.tsDirective(Ares3OfficeManagementAppointmentResourcePage));
})(officeManagement || (officeManagement = {}));

var officeManagement;
(function (officeManagement) {
    var Ares3OfficeManagementBusinessRulePage = /** @class */ (function () {
        function Ares3OfficeManagementBusinessRulePage(appNav, aresModalShelf) {
            var _this = this;
            this.appNav = appNav;
            this.aresModalShelf = aresModalShelf;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\">\n                <ares-tab states=\"states\"   commands=\"commands\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope) {
                var TabItem = _this.appNav.TabItem;
                $scope.states = [new TabItem('officeManagement.businessRule.workflowApproval', '审批管理', '', 'workflowManagement.approval')];
                var toggleSettingSlide = function () {
                    var shelfInstance = _this.aresModalShelf.open({
                        title: '审批管理设置',
                        template: '<workflow-setting-approval-view></workflow-setting-approval-view>',
                        customWidth: '1000px'
                    });
                };
                var commandOption = { permissionCode: 'setting.approval' };
                // @ts-ignore
                $scope.commands = [new Ares.TabCommand('设置', toggleSettingSlide, 'lc-btn lc-btn-primary', 0, commandOption)];
            };
        }
        Ares3OfficeManagementBusinessRulePage.$inject = ['appNav', 'aresModalShelf'];
        return Ares3OfficeManagementBusinessRulePage;
    }());
    officeManagementModule.directive('ares3OfficeManagementBusinessRulePage', Ares.tsDirective(Ares3OfficeManagementBusinessRulePage));
})(officeManagement || (officeManagement = {}));

var officeManagement;
(function (officeManagement) {
    var Ares3OfficeManagementHandoverPage = /** @class */ (function () {
        function Ares3OfficeManagementHandoverPage(appNav, dataDicSvc) {
            var _this = this;
            this.appNav = appNav;
            this.dataDicSvc = dataDicSvc;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\">\n                <ares-tab states=\"states\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope) {
                _this.dataDicSvc.officeSettingDic.load().then(function (officeSetting) {
                    var TabItem = _this.appNav.TabItem;
                    var states = [new TabItem('officeManagement.handover.patient', '人员交接', '', 'setting.patientHandOver')];
                    if (officeSetting && officeSetting.isDeductionChargeEnabled === true) {
                        states.push(new TabItem('officeManagement.handover.chargeDeduction', '划扣执行交接', '', 'setting.chargeDeductionHandOver'));
                    }
                    $scope.states = states;
                });
            };
        }
        Ares3OfficeManagementHandoverPage.$inject = ['appNav', 'dataDicSvc'];
        return Ares3OfficeManagementHandoverPage;
    }());
    officeManagementModule.directive('ares3OfficeManagementHandoverPage', Ares.tsDirective(Ares3OfficeManagementHandoverPage));
})(officeManagement || (officeManagement = {}));

var officeManagement;
(function (officeManagement) {
    var Ares3OfficeManagementSchedulePage = /** @class */ (function () {
        function Ares3OfficeManagementSchedulePage(appNav, aresModalShelf, moduleOptionProvider) {
            var _this = this;
            this.appNav = appNav;
            this.aresModalShelf = aresModalShelf;
            this.moduleOptionProvider = moduleOptionProvider;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\">\n                <ares-tab states=\"states\"  commands=\"commands\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope, element, attrs) {
                var TabItem = _this.appNav.TabItem;
                var settingTabs;
                if (_this.moduleOptionProvider.isProviderSchedule3Enabled()) {
                    $scope.states = [
                        new TabItem('officeManagement.schedule.weekly', '周排班', '', 'schedule.doctor'),
                        new TabItem('officeManagement.schedule.monthly', '月排班', '', 'schedule.doctor'),
                        new TabItem('officeManagement.schedule.weeklyBrowse', '公司排班概览', '', 'schedule.tenant'),
                        new TabItem('officeManagement.schedule.fixed', '固定排班设置', '', 'schedule.doctor'),
                        new TabItem('officeManagement.schedule.attendanceList', '打卡记录', '', 'schedule.attendanceList'),
                        new TabItem('officeManagement.schedule.attendanceDayList', '考勤报表', '', 'schedule.attendanceList'),
                    ];
                    settingTabs = [
                        {
                            title: '考勤配置',
                            template: '<schedule-attendance-config-view></schedule-attendance-config-view>'
                        }
                    ];
                }
                else {
                    $scope.states = [
                        new TabItem('officeManagement.schedule.doctor', '诊所医生排班', '', 'schedule.doctor'),
                        new TabItem('officeManagement.schedule.tenant', '公司排班概览', '', 'schedule.tenant'),
                        new TabItem('officeManagement.schedule.attendanceList', '打卡记录', '', 'schedule.attendanceList'),
                        new TabItem('officeManagement.schedule.attendanceDayList', '考勤报表', '', 'schedule.attendanceList'),
                    ];
                    settingTabs = [
                        {
                            title: '班次配置',
                            template: '<ares3-schedule-rule-view-new></ares3-schedule-rule-view-new>',
                            setDefault: true
                        },
                        {
                            title: '考勤配置',
                            template: '<schedule-attendance-config-view></schedule-attendance-config-view>'
                        }
                    ];
                }
                var toggleSettingSlide = function () {
                    var shelfInstance = _this.aresModalShelf.open({ tabs: settingTabs });
                };
                var commandOption = { permissionCode: 'schedule.rule|schedule.attendanceConfig' };
                // @ts-ignore
                $scope.commands = [new Ares.TabCommand('设置', toggleSettingSlide, 'lc-btn lc-btn-primary', 0, commandOption)];
            };
        }
        Ares3OfficeManagementSchedulePage.$inject = ['appNav', 'aresModalShelf', 'moduleOptionProvider'];
        return Ares3OfficeManagementSchedulePage;
    }());
    officeManagementModule.directive('ares3OfficeManagementSchedulePage', Ares.tsDirective(Ares3OfficeManagementSchedulePage));
})(officeManagement || (officeManagement = {}));

var officeManagement;
(function (officeManagement) {
    var Ares3OfficeManagementStaffPage = /** @class */ (function () {
        function Ares3OfficeManagementStaffPage(appNav, moduleOptionProvider, loginContext) {
            var _this = this;
            this.appNav = appNav;
            this.moduleOptionProvider = moduleOptionProvider;
            this.loginContext = loginContext;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\">\n                <ares-tab states=\"states\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope) {
                var TabItem = _this.appNav.TabItem;
                $scope.states = [
                    new TabItem('officeManagement.staff.list', '员工管理', '', 'setting.provider', ['officeManagement.staff.edit']),
                    new TabItem('officeManagement.staff.role', '角色管理', '', 'setting.role'),
                ];
                if (_this.moduleOptionProvider.isPartnerMgmtEnabled() && _this.loginContext.isGroup) {
                    $scope.states.push(new TabItem('officeManagement.staff.partnerAccountManagement', '外部账号管理', 'icon-users', 'setting.partnerUserManagement'));
                }
            };
        }
        Ares3OfficeManagementStaffPage.$inject = ['appNav', 'moduleOptionProvider', 'loginContext'];
        return Ares3OfficeManagementStaffPage;
    }());
    officeManagementModule.directive('ares3OfficeManagementStaffPage', Ares.tsDirective(Ares3OfficeManagementStaffPage));
})(officeManagement || (officeManagement = {}));

var officeManagement;
(function (officeManagement) {
    var Ares3OfficePointPage = /** @class */ (function () {
        function Ares3OfficePointPage(appNav) {
            var _this = this;
            this.appNav = appNav;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\">\n                <ares-tab states=\"states\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope) {
                var TabItem = _this.appNav.TabItem;
                $scope.states = [new TabItem('officeManagement.officeAccount.setting', '诊所账户', 'glyphicon glyphicon-home', 'tenantSettings.account')];
            };
        }
        Ares3OfficePointPage.$inject = ['appNav'];
        return Ares3OfficePointPage;
    }());
    officeManagementModule.directive('ares3OfficePointPage', Ares.tsDirective(Ares3OfficePointPage));
})(officeManagement || (officeManagement = {}));

var patient;
(function (patient) {
    'use strict';
    var Ares3PatientAppointmentEditModalCtrl = /** @class */ (function () {
        function Ares3PatientAppointmentEditModalCtrl($scope, hebePortal, host, $modalInstance) {
            var _this = this;
            this.$scope = $scope;
            this.hebePortal = hebePortal;
            this.host = host;
            this.$modalInstance = $modalInstance;
            $scope.init = function () {
                _this.hebePortal.registerOnce('ares.hebeModal.imReady', function (data, uniqId) {
                    _this.uniqId = uniqId;
                    console.log('uniqId', uniqId);
                    var appt = _this.host.appt;
                    if (appt.patient) {
                        delete appt.patient.parent;
                        delete appt.patient._events;
                        delete appt.patient._handlers;
                    }
                    _this.hebePortal.post('hebe.hebeModal.config', {
                        modalName: 'apptEdit',
                        data: {
                            appt: _this.host.appt,
                            action: _this.host.action,
                        },
                        uniqId: _this.uniqId,
                    });
                });
                _this.listenOnceForCloseMessage();
            };
        }
        Ares3PatientAppointmentEditModalCtrl.prototype.listenOnceForCloseMessage = function () {
            var _this = this;
            this.hebePortal.registerOnce('ares.hebeModal.close', function (data, uniqId) {
                if (uniqId !== _this.uniqId) {
                    _this.listenOnceForCloseMessage();
                    return;
                }
                console.log('close data', data);
                _this.$modalInstance.close(data);
            });
        };
        Ares3PatientAppointmentEditModalCtrl.$inject = ['$scope', 'hebePortal', 'host', '$modalInstance'];
        return Ares3PatientAppointmentEditModalCtrl;
    }());
    var Ares3PatientAppointmentEditModalView = /** @class */ (function () {
        function Ares3PatientAppointmentEditModalView() {
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div style=\"width: 100%; height: 100%;\">\n                <ares-new-home-view target-route=\"modalEntry\"></ares-new-home-view>\n            </div>\n        ";
            this.link = function ($scope) {
                $scope.init();
            };
        }
        Ares3PatientAppointmentEditModalView.$inject = [];
        return Ares3PatientAppointmentEditModalView;
    }());
    patientModule.controller('Ares3PatientAppointmentEditModalCtrl', Ares.tsController(Ares3PatientAppointmentEditModalCtrl));
    patientModule.directive('ares3PatientAppointmentEditModalView', Ares.tsDirective(Ares3PatientAppointmentEditModalView));
})(patient || (patient = {}));

var patient;
(function (patient) {
    'use strict';
    var Ares3PatientCheckInModalCtrl = /** @class */ (function () {
        function Ares3PatientCheckInModalCtrl($scope, hebePortal, host, $modalInstance) {
            var _this = this;
            this.$scope = $scope;
            this.hebePortal = hebePortal;
            this.host = host;
            this.$modalInstance = $modalInstance;
            $scope.init = function () {
                _this.hebePortal.registerOnce('ares.hebeModal.imReady', function (data, uniqId) {
                    _this.uniqId = uniqId;
                    var appt = _this.host.appt;
                    if (appt && appt.patient) {
                        delete appt.patient.parent;
                        delete appt.patient._events;
                        delete appt.patient._handlers;
                    }
                    _this.hebePortal.post('hebe.hebeModal.config', {
                        modalName: 'checkIn',
                        data: {
                            patientId: _this.host.patientId,
                            appt: _this.host.appt,
                        },
                        uniqId: _this.uniqId,
                    });
                });
                _this.listenOnceForCloseMessage();
            };
        }
        Ares3PatientCheckInModalCtrl.prototype.listenOnceForCloseMessage = function () {
            var _this = this;
            this.hebePortal.registerOnce('ares.hebeModal.close', function (data, uniqId) {
                if (uniqId !== _this.uniqId) {
                    _this.listenOnceForCloseMessage();
                    return;
                }
                _this.$modalInstance.close(data);
            });
        };
        Ares3PatientCheckInModalCtrl.$inject = ['$scope', 'hebePortal', 'host', '$modalInstance'];
        return Ares3PatientCheckInModalCtrl;
    }());
    var Ares3PatientCheckInModalView = /** @class */ (function () {
        function Ares3PatientCheckInModalView() {
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div style=\"width: 100%; height: 100%;\">\n                <ares-new-home-view target-route=\"modalEntry\"></ares-new-home-view>\n            </div>\n        ";
            this.link = function ($scope) {
                $scope.init();
            };
        }
        Ares3PatientCheckInModalView.$inject = [];
        return Ares3PatientCheckInModalView;
    }());
    patientModule.controller('Ares3PatientCheckInModalCtrl', Ares.tsController(Ares3PatientCheckInModalCtrl));
    patientModule.directive('ares3PatientCheckInModalView', Ares.tsDirective(Ares3PatientCheckInModalView));
})(patient || (patient = {}));

var patientManagement;
(function (patientManagement) {
    var Ares3PatientManagementArchivedPage = /** @class */ (function () {
        function Ares3PatientManagementArchivedPage(appNav) {
            var _this = this;
            this.appNav = appNav;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\" style=\"height: calc(100vh - 58px)\">\n                <ares-tab states=\"states\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope) {
                var TabItem = _this.appNav.TabItem;
                $scope.states = [
                    new TabItem('newPatientManagement.archived.list', '归档患者', '', 'patientCenter.archivedPatient'),
                ];
            };
        }
        Ares3PatientManagementArchivedPage.$inject = ['appNav'];
        return Ares3PatientManagementArchivedPage;
    }());
    patientManagementModule.directive('ares3PatientManagementArchivedPage', Ares.tsDirective(Ares3PatientManagementArchivedPage));
})(patientManagement || (patientManagement = {}));

var officeManagement;
(function (officeManagement) {
    var Ares3PatientManagementConsultPage = /** @class */ (function () {
        function Ares3PatientManagementConsultPage(appNav, aresModalShelf) {
            var _this = this;
            this.appNav = appNav;
            this.aresModalShelf = aresModalShelf;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\">\n                <ares-tab states=\"states\" commands=\"commands\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope) {
                var TabItem = _this.appNav.TabItem;
                $scope.states = [
                    new TabItem('newPatientManagement.consult.networkList', '网电咨询', '', 'consultCenter.consultList'),
                    new TabItem('newPatientManagement.consult.list', '现场咨询', '', 'consultCenter.list'),
                    new TabItem('newPatientManagement.consult.onSiteList', '现场咨询任务列表', '', 'consultCenter.list'),
                ];
                var toggleSettingSlide = function () {
                    var shelfInstance = _this.aresModalShelf.open({
                        title: '成交意愿',
                        template: '<consult-intention-view></consult-intention-view>',
                        customWidth: '1000px'
                    });
                };
                var commandOption = { permissionCode: 'consultCenter.willingParties' };
                // @ts-ignore
                $scope.commands = [new Ares.TabCommand('设置', toggleSettingSlide, 'lc-btn lc-btn-primary', 0, commandOption)];
            };
        }
        Ares3PatientManagementConsultPage.$inject = ['appNav', 'aresModalShelf'];
        return Ares3PatientManagementConsultPage;
    }());
    officeManagementModule.directive('ares3PatientManagementConsultPage', Ares.tsDirective(Ares3PatientManagementConsultPage));
})(officeManagement || (officeManagement = {}));

var patientManagement;
(function (patientManagement) {
    var Ares3PatientManagementDuplicatePage = /** @class */ (function () {
        function Ares3PatientManagementDuplicatePage(appNav) {
            var _this = this;
            this.appNav = appNav;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\" style=\"height: calc(100vh - 58px)\">\n                <ares-tab states=\"states\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope) {
                var TabItem = _this.appNav.TabItem;
                $scope.states = [
                    new TabItem('newPatientManagement.duplicate.list', '重复患者', '', 'patientCenter.duplicatedPatient'),
                ];
            };
        }
        Ares3PatientManagementDuplicatePage.$inject = ['appNav'];
        return Ares3PatientManagementDuplicatePage;
    }());
    patientManagementModule.directive('ares3PatientManagementDuplicatePage', Ares.tsDirective(Ares3PatientManagementDuplicatePage));
})(patientManagement || (patientManagement = {}));

var officeManagement;
(function (officeManagement) {
    var Ares3PatientManagementFollowupPage = /** @class */ (function () {
        function Ares3PatientManagementFollowupPage(appNav, aresModalShelf, permissionProvider) {
            var _this = this;
            this.appNav = appNav;
            this.aresModalShelf = aresModalShelf;
            this.permissionProvider = permissionProvider;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\">\n                <ares-tab states=\"states\" commands=\"commands\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope) {
                var TabItem = _this.appNav.TabItem;
                $scope.states = [
                    new TabItem('newPatientManagement.followup.list', '随访记录', '', 'followup.list'),
                    new TabItem('newPatientManagement.followup.last', '最近随访', '', 'followup.last'),
                ];
                var toggleSettingSlide = function () {
                    var tabs = [{
                            title: '随访模板',
                            template: '<followup-template-list-view></followup-template-list-view>',
                            setDefault: true
                        }];
                    if (_this.permissionProvider.isAllowed('followup.content')) {
                        tabs.push({
                            title: '随访内容模板',
                            template: '<followup-content-list-view></followup-content-list-view>'
                        });
                    }
                    if (_this.permissionProvider.isAllowed('followup.result')) {
                        tabs.push({
                            title: '随访结果模板',
                            template: '<followup-result-list-view></followup-result-list-view>'
                        });
                    }
                    tabs.push({
                        title: '自动随访规则',
                        template: '<followup-auto-rule-list-view></followup-auto-rule-list-view>'
                    });
                    var shelfInstance = _this.aresModalShelf.open({ tabs: tabs, customWidth: '840px' });
                };
                // @ts-ignore
                $scope.commands = [new Ares.TabCommand('设置', toggleSettingSlide, 'lc-btn lc-btn-primary', 0)];
            };
        }
        Ares3PatientManagementFollowupPage.$inject = ['appNav', 'aresModalShelf', 'permissionProvider'];
        return Ares3PatientManagementFollowupPage;
    }());
    officeManagementModule.directive('ares3PatientManagementFollowupPage', Ares.tsDirective(Ares3PatientManagementFollowupPage));
})(officeManagement || (officeManagement = {}));

var patientManagement;
(function (patientManagement) {
    var Ares3PatientManagementImportPage = /** @class */ (function () {
        function Ares3PatientManagementImportPage(appNav) {
            var _this = this;
            this.appNav = appNav;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\" style=\"height: calc(100vh - 58px)\">\n                <ares-tab states=\"states\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope) {
                var TabItem = _this.appNav.TabItem;
                $scope.states = [
                    new TabItem('newPatientManagement.import.list', '患者导入', '', 'dataImport.patient'),
                ];
            };
        }
        Ares3PatientManagementImportPage.$inject = ['appNav'];
        return Ares3PatientManagementImportPage;
    }());
    patientManagementModule.directive('ares3PatientManagementImportPage', Ares.tsDirective(Ares3PatientManagementImportPage));
})(patientManagement || (patientManagement = {}));

var officeManagement;
(function (officeManagement) {
    var Ares3PatientManagementRevisitPage = /** @class */ (function () {
        function Ares3PatientManagementRevisitPage(appNav, aresModalShelf) {
            var _this = this;
            this.appNav = appNav;
            this.aresModalShelf = aresModalShelf;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\">\n                <ares-tab states=\"states\"    commands=\"commands\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope) {
                var TabItem = _this.appNav.TabItem;
                $scope.states = [
                    new TabItem('newPatientManagement.revisit.list', '回访记录', '', 'ReturnVisitFolder.list'),
                ];
                var toggleSettingSlide = function () {
                    var shelfInstance = _this.aresModalShelf.open({
                        title: '自动回访规则',
                        template: '<group-auto-revisit-rule-view></group-auto-revisit-rule-view>',
                        customWidth: '1000px'
                    });
                };
                var commandOption = { permissionCode: 'patientMgmt.autoRevisitRule' };
                // @ts-ignore
                $scope.commands = [new Ares.TabCommand('设置', toggleSettingSlide, 'lc-btn lc-btn-primary', 0, commandOption)];
            };
        }
        Ares3PatientManagementRevisitPage.$inject = ['appNav', 'aresModalShelf'];
        return Ares3PatientManagementRevisitPage;
    }());
    officeManagementModule.directive('ares3PatientManagementRevisitPage', Ares.tsDirective(Ares3PatientManagementRevisitPage));
})(officeManagement || (officeManagement = {}));

var reportCenter;
(function (reportCenter) {
    var Ares3ReportCenterFamilyConsumptionPage = /** @class */ (function () {
        function Ares3ReportCenterFamilyConsumptionPage(appNav, officeOptionSvc, moduleOptionProvider, enums, localCache, loginContext, ares3NavItemProvider) {
            var _this = this;
            this.appNav = appNav;
            this.officeOptionSvc = officeOptionSvc;
            this.moduleOptionProvider = moduleOptionProvider;
            this.enums = enums;
            this.localCache = localCache;
            this.loginContext = loginContext;
            this.ares3NavItemProvider = ares3NavItemProvider;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\">\n                <ares-tab states=\"states\" commands=\"commands\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope) {
                var setStates = function () {
                    var TabItem = _this.appNav.TabItem;
                    $scope.states = [
                        new TabItem('reportCenter.familyConsumption.report', '家庭消费统计', '', 'financev2.familyConsumptionRepot'),
                    ];
                };
                var setCommands = function () {
                    _this.officeOptionSvc.getOfficeOption(_this.officeOptionSvc.optionKeys.PaymentTypeUpgradeStatus).then(function (upgradeStatus) {
                        upgradeStatus = parseInt(upgradeStatus);
                        // 新开户默认使用新报表的，不能切回老报表
                        if (upgradeStatus !== _this.enums.PaymentTypeUpgradeStatus.InitUpgraded) {
                            $scope.commands = [{
                                    text: "切换到旧版",
                                    className: 'financev2SwitchBtn',
                                    commandType: _this.enums.CommandType.Button,
                                    onExecute: function () {
                                        returnOldFinance();
                                    }
                                }];
                        }
                    });
                };
                var returnOldFinance = function () {
                    var reportCacheKey = _this.localCache.getCacheKey(_this.localCache.keys.IsNewFinanceReportEnabled, _this.loginContext.officeId);
                    var reportCache = _this.localCache.getCache(reportCacheKey);
                    reportCache.clear();
                    var financeNavItem = _this.ares3NavItemProvider.findNavItem('finance');
                    financeNavItem.isVisible = true;
                    var financev2NavItem = _this.ares3NavItemProvider.findNavItem('financev2');
                    financev2NavItem.isVisible = false;
                    _this.appNav.goToState('finance');
                };
                (function () {
                    setStates();
                    setCommands();
                })();
            };
        }
        Ares3ReportCenterFamilyConsumptionPage.$inject = ['appNav', 'officeOptionSvc', 'moduleOptionProvider', 'enums', 'localCache', 'loginContext', 'ares3NavItemProvider'];
        return Ares3ReportCenterFamilyConsumptionPage;
    }());
    reportCenterModule.directive('ares3ReportCenterFamilyConsumptionPage', Ares.tsDirective(Ares3ReportCenterFamilyConsumptionPage));
})(reportCenter || (reportCenter = {}));

var reportCenter;
(function (reportCenter) {
    var Ares3ReportCenterFinanceCalendarPage = /** @class */ (function () {
        function Ares3ReportCenterFinanceCalendarPage(appNav, officeOptionSvc, moduleOptionProvider, enums, localCache, loginContext, ares3NavItemProvider) {
            var _this = this;
            this.appNav = appNav;
            this.officeOptionSvc = officeOptionSvc;
            this.moduleOptionProvider = moduleOptionProvider;
            this.enums = enums;
            this.localCache = localCache;
            this.loginContext = loginContext;
            this.ares3NavItemProvider = ares3NavItemProvider;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\">\n                <ares-tab states=\"states\" commands=\"commands\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope) {
                var setStates = function () {
                    var TabItem = _this.appNav.TabItem;
                    $scope.states = [
                        new TabItem('reportCenter.financeCalendar.calendar', '对账日历', '', 'financev2.checkCalendar'),
                    ];
                };
                var setCommands = function () {
                    _this.officeOptionSvc.getOfficeOption(_this.officeOptionSvc.optionKeys.PaymentTypeUpgradeStatus).then(function (upgradeStatus) {
                        upgradeStatus = parseInt(upgradeStatus);
                        // 新开户默认使用新报表的，不能切回老报表
                        if (upgradeStatus !== _this.enums.PaymentTypeUpgradeStatus.InitUpgraded) {
                            $scope.commands = [{
                                    text: "切换到旧版",
                                    className: 'financev2SwitchBtn',
                                    commandType: _this.enums.CommandType.Button,
                                    onExecute: function () {
                                        returnOldFinance();
                                    }
                                }];
                        }
                    });
                };
                var returnOldFinance = function () {
                    var reportCacheKey = _this.localCache.getCacheKey(_this.localCache.keys.IsNewFinanceReportEnabled, _this.loginContext.officeId);
                    var reportCache = _this.localCache.getCache(reportCacheKey);
                    reportCache.clear();
                    var financeNavItem = _this.ares3NavItemProvider.findNavItem('finance');
                    financeNavItem.isVisible = true;
                    var financev2NavItem = _this.ares3NavItemProvider.findNavItem('financev2');
                    financev2NavItem.isVisible = false;
                    _this.appNav.goToState('finance');
                };
                (function () {
                    setStates();
                    setCommands();
                })();
            };
        }
        Ares3ReportCenterFinanceCalendarPage.$inject = ['appNav', 'officeOptionSvc', 'moduleOptionProvider', 'enums', 'localCache', 'loginContext', 'ares3NavItemProvider'];
        return Ares3ReportCenterFinanceCalendarPage;
    }());
    reportCenterModule.directive('ares3ReportCenterFinanceCalendarPage', Ares.tsDirective(Ares3ReportCenterFinanceCalendarPage));
})(reportCenter || (reportCenter = {}));

var reportCenter;
(function (reportCenter) {
    var Ares3ReportCenterOverduePatientPage = /** @class */ (function () {
        function Ares3ReportCenterOverduePatientPage(appNav, officeOptionSvc, moduleOptionProvider, enums, localCache, loginContext, ares3NavItemProvider) {
            var _this = this;
            this.appNav = appNav;
            this.officeOptionSvc = officeOptionSvc;
            this.moduleOptionProvider = moduleOptionProvider;
            this.enums = enums;
            this.localCache = localCache;
            this.loginContext = loginContext;
            this.ares3NavItemProvider = ares3NavItemProvider;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\">\n                <ares-tab states=\"states\" commands=\"commands\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope) {
                var setStates = function () {
                    var TabItem = _this.appNav.TabItem;
                    $scope.states = [
                        new TabItem('reportCenter.overduePatient.report', '欠费患者', '', 'financev2.overduePatientReport'),
                    ];
                };
                var setCommands = function () {
                    _this.officeOptionSvc.getOfficeOption(_this.officeOptionSvc.optionKeys.PaymentTypeUpgradeStatus).then(function (upgradeStatus) {
                        upgradeStatus = parseInt(upgradeStatus);
                        // 新开户默认使用新报表的，不能切回老报表
                        if (upgradeStatus !== _this.enums.PaymentTypeUpgradeStatus.InitUpgraded) {
                            $scope.commands = [{
                                    text: "切换到旧版",
                                    className: 'financev2SwitchBtn',
                                    commandType: _this.enums.CommandType.Button,
                                    onExecute: function () {
                                        returnOldFinance();
                                    }
                                }];
                        }
                    });
                };
                var returnOldFinance = function () {
                    var reportCacheKey = _this.localCache.getCacheKey(_this.localCache.keys.IsNewFinanceReportEnabled, _this.loginContext.officeId);
                    var reportCache = _this.localCache.getCache(reportCacheKey);
                    reportCache.clear();
                    var financeNavItem = _this.ares3NavItemProvider.findNavItem('finance');
                    financeNavItem.isVisible = true;
                    var financev2NavItem = _this.ares3NavItemProvider.findNavItem('financev2');
                    financev2NavItem.isVisible = false;
                    _this.appNav.goToState('finance');
                };
                (function () {
                    setStates();
                    setCommands();
                })();
            };
        }
        Ares3ReportCenterOverduePatientPage.$inject = ['appNav', 'officeOptionSvc', 'moduleOptionProvider', 'enums', 'localCache', 'loginContext', 'ares3NavItemProvider'];
        return Ares3ReportCenterOverduePatientPage;
    }());
    reportCenterModule.directive('ares3ReportCenterOverduePatientPage', Ares.tsDirective(Ares3ReportCenterOverduePatientPage));
})(reportCenter || (reportCenter = {}));

var reportCenter;
(function (reportCenter) {
    var Ares3ReportCenterMinePage = /** @class */ (function () {
        function Ares3ReportCenterMinePage(appNav, loginContext) {
            var _this = this;
            this.appNav = appNav;
            this.loginContext = loginContext;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\">\n                <ares-tab states=\"states\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope) {
                var TabItem = _this.appNav.TabItem;
                var states = [
                    new TabItem('reportCenter.mine.offline', '离线报表', '', 'finance.myReport'),
                ];
                if (_this.loginContext.providerJob === '咨询师') {
                    states = states.concat([
                        new TabItem('reportCenter.mine.chargeDetail', '账单明细', '', 'myReport.all'),
                        new TabItem('reportCenter.mine.chargeItemDetail', '项目明细', '', 'myReport.all'),
                        new TabItem('reportCenter.mine.overduePatient', '欠费患者', '', 'myReport.all'),
                        new TabItem('reportCenter.mine.membershipBalance', '储值卡余额', '', 'myReport.all'),
                        new TabItem('reportCenter.mine.membershipSummary', '储值卡余额变动记录', '', 'myReport.all'),
                        new TabItem('reportCenter.mine.consultantReport', '咨询师工作汇总', '', 'myReport.all'),
                    ]);
                }
                $scope.states = states;
            };
        }
        Ares3ReportCenterMinePage.$inject = ['appNav', 'loginContext'];
        return Ares3ReportCenterMinePage;
    }());
    reportCenterModule.directive('ares3ReportCenterMinePage', Ares.tsDirective(Ares3ReportCenterMinePage));
})(reportCenter || (reportCenter = {}));

var reportCenter;
(function (reportCenter) {
    var Ares3ReportCenterAppointmentPage = /** @class */ (function () {
        function Ares3ReportCenterAppointmentPage(appNav, officeOptionSvc, dataDicSvc) {
            var _this = this;
            this.appNav = appNav;
            this.officeOptionSvc = officeOptionSvc;
            this.dataDicSvc = dataDicSvc;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper ares3-report-center-appointment-page\">\n                <style>\n                    .ares3-report-center-appointment-page .report-menu-view {\n                        display: none;;\n                    }\n                    .ares3-report-center-appointment-page .report-content {\n                        padding: 0 !important;\n                    }\n                </style>\n                <ares-tab states=\"states\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope) {
                var reportSetConfigs;
                var TabItem = _this.appNav.TabItem;
                var fillReportSet = function (navItems, setState, setName) {
                    var reportSet = _(reportSetConfigs).find(function (c) {
                        return c.name === setName;
                    });
                    if (reportSet && reportSet.reports && reportSet.reports.length > 0) {
                        var setPermission = null;
                        if (_(reportSet.reports).every(function (r) { return r.permissionCode; })) {
                            setPermission = _(reportSet.reports).pluck('permissionCode').join('|');
                        }
                        navItems.push(new TabItem(setState, reportSet.displayName, '', setPermission));
                    }
                };
                _this.dataDicSvc.reportSetConfigDic.load().then(function (data) {
                    reportSetConfigs = data;
                    var states = [
                        new TabItem('reportCenter.appointment.summary', '预约分析', '', 'operation.apptAnalysis'),
                        new TabItem('reportCenter.appointment.trend', '预约趋势', '', 'tenantReport.apptTrend'),
                    ];
                    fillReportSet(states, 'reportCenter.appointment.attendance', 'PatientAppointmentAnalysisReportSet');
                    $scope.states = states;
                });
            };
        }
        Ares3ReportCenterAppointmentPage.$inject = ['appNav', 'officeOptionSvc', 'dataDicSvc'];
        return Ares3ReportCenterAppointmentPage;
    }());
    reportCenterModule.directive('ares3ReportCenterAppointmentPage', Ares.tsDirective(Ares3ReportCenterAppointmentPage));
})(reportCenter || (reportCenter = {}));

var reportCenter;
(function (reportCenter) {
    var Ares3ReportCenterMarketingPage = /** @class */ (function () {
        function Ares3ReportCenterMarketingPage(appNav, officeOptionSvc) {
            var _this = this;
            this.appNav = appNav;
            this.officeOptionSvc = officeOptionSvc;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\">\n                <ares-tab states=\"states\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope) {
                var TabItem = _this.appNav.TabItem;
                $scope.states = [
                    new TabItem('reportCenter.marketing.gift', '卡券管理', '', 'operation.gift'),
                ];
            };
        }
        Ares3ReportCenterMarketingPage.$inject = ['appNav', 'officeOptionSvc'];
        return Ares3ReportCenterMarketingPage;
    }());
    reportCenterModule.directive('ares3ReportCenterMarketingPage', Ares.tsDirective(Ares3ReportCenterMarketingPage));
})(reportCenter || (reportCenter = {}));

var reportCenter;
(function (reportCenter) {
    var Ares3ReportCenterOperationPage = /** @class */ (function () {
        function Ares3ReportCenterOperationPage(appNav, officeOptionSvc) {
            var _this = this;
            this.appNav = appNav;
            this.officeOptionSvc = officeOptionSvc;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\">\n                <ares-tab states=\"states\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope) {
                var TabItem = _this.appNav.TabItem;
                $scope.states = [
                    new TabItem('reportCenter.operation.analysis', '运营分析统计', '', 'operation.analysis'),
                ];
            };
        }
        Ares3ReportCenterOperationPage.$inject = ['appNav', 'officeOptionSvc'];
        return Ares3ReportCenterOperationPage;
    }());
    reportCenterModule.directive('ares3ReportCenterOperationPage', Ares.tsDirective(Ares3ReportCenterOperationPage));
})(reportCenter || (reportCenter = {}));

var reportCenter;
(function (reportCenter) {
    var Ares3ReportCenterPatientPage = /** @class */ (function () {
        function Ares3ReportCenterPatientPage(appNav, officeOptionSvc) {
            var _this = this;
            this.appNav = appNav;
            this.officeOptionSvc = officeOptionSvc;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\">\n                <ares-tab states=\"states\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope) {
                var TabItem = _this.appNav.TabItem;
                _this.officeOptionSvc.getOfficeOption(_this.officeOptionSvc.optionKeys.IsNewPaymentTypeEnabled).then(function (isNewPaymentTypeEnabled) {
                    var states = [
                        new TabItem('reportCenter.patient.summary', '患者分析', '', 'operation.patienttAnalysis'),
                        new TabItem('reportCenter.patient.newPatient', '新增患者', '', 'tenantReport.newPatients'),
                        new TabItem('reportCenter.patient.referrer', '推荐人分析', '', 'operation.referrer'),
                        new TabItem('reportCenter.patient.source', '患者来源分析', '', 'operation.patientSource'),
                    ];
                    if (isNewPaymentTypeEnabled) {
                        states.push(new TabItem('reportCenter.patient.consumption', '患者消费统计', '', 'finance.patientConsumption'));
                    }
                    $scope.states = states;
                });
            };
        }
        Ares3ReportCenterPatientPage.$inject = ['appNav', 'officeOptionSvc'];
        return Ares3ReportCenterPatientPage;
    }());
    reportCenterModule.directive('ares3ReportCenterPatientPage', Ares.tsDirective(Ares3ReportCenterPatientPage));
})(reportCenter || (reportCenter = {}));

var reportCenter;
(function (reportCenter) {
    var Ares3ReportCenterRevenuePage = /** @class */ (function () {
        function Ares3ReportCenterRevenuePage(appNav, officeOptionSvc) {
            var _this = this;
            this.appNav = appNav;
            this.officeOptionSvc = officeOptionSvc;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\">\n                <ares-tab states=\"states\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope) {
                var TabItem = _this.appNav.TabItem;
                $scope.states = [
                    new TabItem('reportCenter.revenue.summary', '营收分析', '', 'operation.amounttAnalysis'),
                    new TabItem('reportCenter.revenue.incomeSummary', '收入统计', '', 'tenantReport.incomeSummary'),
                    new TabItem('reportCenter.revenue.incomeTrend', '收入趋势', '', 'tenantReport.incomeTrend'),
                ];
            };
        }
        Ares3ReportCenterRevenuePage.$inject = ['appNav', 'officeOptionSvc'];
        return Ares3ReportCenterRevenuePage;
    }());
    reportCenterModule.directive('ares3ReportCenterRevenuePage', Ares.tsDirective(Ares3ReportCenterRevenuePage));
})(reportCenter || (reportCenter = {}));

var reportCenter;
(function (reportCenter) {
    var Ares3ReportCenterApptPerformancePage = /** @class */ (function () {
        function Ares3ReportCenterApptPerformancePage(appNav, officeOptionSvc) {
            var _this = this;
            this.appNav = appNav;
            this.officeOptionSvc = officeOptionSvc;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\">\n                <ares-tab states=\"states\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope) {
                var TabItem = _this.appNav.TabItem;
                $scope.states = [
                    new TabItem('reportCenter.apptPerformance.report', '预约绩效查询', '', 'performancev2.doctorApptPerformance'),
                ];
            };
        }
        Ares3ReportCenterApptPerformancePage.$inject = ['appNav', 'officeOptionSvc'];
        return Ares3ReportCenterApptPerformancePage;
    }());
    //ares3-report-center-appt-performance-page
    reportCenterModule.directive('ares3ReportCenterApptPerformancePage', Ares.tsDirective(Ares3ReportCenterApptPerformancePage));
})(reportCenter || (reportCenter = {}));

var reportCenter;
(function (reportCenter) {
    var Ares3ReportCenterAssistantWorkPage = /** @class */ (function () {
        function Ares3ReportCenterAssistantWorkPage(appNav, officeOptionSvc) {
            var _this = this;
            this.appNav = appNav;
            this.officeOptionSvc = officeOptionSvc;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\">\n                <ares-tab states=\"states\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope) {
                var TabItem = _this.appNav.TabItem;
                $scope.states = [
                    new TabItem('reportCenter.assistantWork.report', '牙医助理工作汇总', '', 'performancev2.assistantWorkReport'),
                ];
            };
        }
        Ares3ReportCenterAssistantWorkPage.$inject = ['appNav', 'officeOptionSvc'];
        return Ares3ReportCenterAssistantWorkPage;
    }());
    reportCenterModule.directive('ares3ReportCenterAssistantWorkPage', Ares.tsDirective(Ares3ReportCenterAssistantWorkPage));
})(reportCenter || (reportCenter = {}));

var reportCenter;
(function (reportCenter) {
    var Ares3ReportCenterMedicalExamPage = /** @class */ (function () {
        function Ares3ReportCenterMedicalExamPage(appNav, officeOptionSvc) {
            var _this = this;
            this.appNav = appNav;
            this.officeOptionSvc = officeOptionSvc;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\">\n                <ares-tab states=\"states\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope) {
                var TabItem = _this.appNav.TabItem;
                $scope.states = [
                    new TabItem('reportCenter.performance.medicalExam', '拍片绩效', '', 'performancev2.medicalExam'),
                ];
            };
        }
        Ares3ReportCenterMedicalExamPage.$inject = ['appNav', 'officeOptionSvc'];
        return Ares3ReportCenterMedicalExamPage;
    }());
    reportCenterModule.directive('ares3ReportCenterMedicalExamPage', Ares.tsDirective(Ares3ReportCenterMedicalExamPage));
})(reportCenter || (reportCenter = {}));

/**
 * 把hebe页面简单地包一层，用作tab下的ui-view
 */
var systemSetting;
(function (systemSetting) {
    'use strict';
    var Ares3SystemSettingAppointmentItemView = /** @class */ (function () {
        function Ares3SystemSettingAppointmentItemView() {
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div style=\"width: 100%; height: 100%;\">\n                <ares-new-home-view target-route=\"systemSetting.appointment.item\"></ares-new-home-view>\n            </div>\n        ";
        }
        Ares3SystemSettingAppointmentItemView.$inject = [];
        return Ares3SystemSettingAppointmentItemView;
    }());
    systemSettingModule.directive('ares3SystemSettingAppointmentItemView', Ares.tsDirective(Ares3SystemSettingAppointmentItemView));
})(systemSetting || (systemSetting = {}));

var systemSetting;
(function (systemSetting) {
    var Ares3SystemSettingAppointmentPage = /** @class */ (function () {
        function Ares3SystemSettingAppointmentPage(appNav, moduleOptionProvider) {
            var _this = this;
            this.appNav = appNav;
            this.moduleOptionProvider = moduleOptionProvider;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\">\n                <ares-tab states=\"states\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope) {
                var TabItem = _this.appNav.TabItem;
                $scope.states = [
                    new _this.appNav.TabItem('systemSetting.appointment.rule', '预约规则', '', 'setting.office&settings.rule'),
                    new _this.appNav.TabItem('systemSetting.appointment.item', '预约项目', '', 'setting.appointment'),
                    new _this.appNav.TabItem('systemSetting.appointment.scheduler', '预约看板', '', 'setting.office&settings.rule'),
                    new _this.appNav.TabItem('systemSetting.appointment.reminding', '预约提醒服务', '', 'setting.office&settings.rule'),
                ];
            };
        }
        Ares3SystemSettingAppointmentPage.$inject = ['appNav', 'moduleOptionProvider'];
        return Ares3SystemSettingAppointmentPage;
    }());
    systemSettingModule.directive('ares3SystemSettingAppointmentPage', Ares.tsDirective(Ares3SystemSettingAppointmentPage));
})(systemSetting || (systemSetting = {}));

/**
 * 把hebe页面简单地包一层，用作tab下的ui-view
 */
var systemSetting;
(function (systemSetting) {
    'use strict';
    var Ares3SystemSettingAppointmentRemindingView = /** @class */ (function () {
        function Ares3SystemSettingAppointmentRemindingView() {
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div style=\"width: 100%; height: 100%;\">\n                <ares-new-home-view target-route=\"systemSetting.appointment.reminding\"></ares-new-home-view>\n            </div>\n        ";
        }
        Ares3SystemSettingAppointmentRemindingView.$inject = [];
        return Ares3SystemSettingAppointmentRemindingView;
    }());
    systemSettingModule.directive('ares3SystemSettingAppointmentRemindingView', Ares.tsDirective(Ares3SystemSettingAppointmentRemindingView));
})(systemSetting || (systemSetting = {}));

/**
 * 把hebe页面简单地包一层，用作tab下的ui-view
 */
var systemSetting;
(function (systemSetting) {
    'use strict';
    var Ares3SystemSettingAppointmentRuleView = /** @class */ (function () {
        function Ares3SystemSettingAppointmentRuleView() {
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div style=\"width: 100%; height: 100%;\">\n                <ares-new-home-view target-route=\"systemSetting.appointment.rule\"></ares-new-home-view>\n            </div>\n        ";
        }
        Ares3SystemSettingAppointmentRuleView.$inject = [];
        return Ares3SystemSettingAppointmentRuleView;
    }());
    systemSettingModule.directive('ares3SystemSettingAppointmentRuleView', Ares.tsDirective(Ares3SystemSettingAppointmentRuleView));
})(systemSetting || (systemSetting = {}));

/**
 * 把hebe页面简单地包一层，用作tab下的ui-view
 */
var systemSetting;
(function (systemSetting) {
    'use strict';
    var Ares3SystemSettingAppointmentSchedulerView = /** @class */ (function () {
        function Ares3SystemSettingAppointmentSchedulerView() {
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div style=\"width: 100%; height: 100%;\">\n                <ares-new-home-view target-route=\"systemSetting.appointment.scheduler\"></ares-new-home-view>\n            </div>\n        ";
        }
        Ares3SystemSettingAppointmentSchedulerView.$inject = [];
        return Ares3SystemSettingAppointmentSchedulerView;
    }());
    systemSettingModule.directive('ares3SystemSettingAppointmentSchedulerView', Ares.tsDirective(Ares3SystemSettingAppointmentSchedulerView));
})(systemSetting || (systemSetting = {}));

/**
 * 把hebe页面简单地包一层，用作tab下的ui-view
 */
var systemSetting;
(function (systemSetting) {
    'use strict';
    var Ares3SystemSettingBusinessCallingSettingView = /** @class */ (function () {
        function Ares3SystemSettingBusinessCallingSettingView() {
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div style=\"width: 100%; height: 100%;\">\n                <ares-new-home-view target-route=\"officeSettings.callingConfig\"></ares-new-home-view>\n            </div>\n        ";
        }
        Ares3SystemSettingBusinessCallingSettingView.$inject = [];
        return Ares3SystemSettingBusinessCallingSettingView;
    }());
    systemSettingModule.directive('ares3SystemSettingBusinessCallingSettingView', Ares.tsDirective(Ares3SystemSettingBusinessCallingSettingView));
})(systemSetting || (systemSetting = {}));

/**
 * 把hebe页面简单地包一层，用作tab下的ui-view
 */
var systemSetting;
(function (systemSetting) {
    'use strict';
    var Ares3SystemSettingBusinessCheckInSettingView = /** @class */ (function () {
        function Ares3SystemSettingBusinessCheckInSettingView() {
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div style=\"width: 100%; height: 100%;\">\n                <ares-new-home-view target-route=\"systemSetting.office.check-in\"></ares-new-home-view>\n            </div>\n        ";
        }
        Ares3SystemSettingBusinessCheckInSettingView.$inject = [];
        return Ares3SystemSettingBusinessCheckInSettingView;
    }());
    systemSettingModule.directive('ares3SystemSettingBusinessCheckInSettingView', Ares.tsDirective(Ares3SystemSettingBusinessCheckInSettingView));
})(systemSetting || (systemSetting = {}));

var systemSetting;
(function (systemSetting) {
    var Ares3SystemSettingChargeFieldPage = /** @class */ (function () {
        function Ares3SystemSettingChargeFieldPage(appNav, moduleOptionProvider) {
            var _this = this;
            this.appNav = appNav;
            this.moduleOptionProvider = moduleOptionProvider;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\">\n                <ares-tab states=\"states\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope) {
                var TabItem = _this.appNav.TabItem;
                $scope.states = [
                    new _this.appNav.TabItem('systemSetting.chargeField.setting', '收费类型设置', '', 'setting.office&settings.chargeInfo'),
                ];
            };
        }
        Ares3SystemSettingChargeFieldPage.$inject = ['appNav', 'moduleOptionProvider'];
        return Ares3SystemSettingChargeFieldPage;
    }());
    systemSettingModule.directive('ares3SystemSettingChargeFieldPage', Ares.tsDirective(Ares3SystemSettingChargeFieldPage));
})(systemSetting || (systemSetting = {}));

var systemSetting;
(function (systemSetting) {
    var Ares3SystemSettingChargeItemPage = /** @class */ (function () {
        function Ares3SystemSettingChargeItemPage(appNav, dataDicSvc, $q) {
            var _this = this;
            this.appNav = appNav;
            this.dataDicSvc = dataDicSvc;
            this.$q = $q;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\">\n                <ares-tab states=\"states\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope) {
                var TabItem = _this.appNav.TabItem;
                _this.$q.all([
                    _this.dataDicSvc.officeSettingDic.load(),
                    _this.dataDicSvc.chargeItemFreeFieldDic.load(),
                ]).then(function (data) {
                    var allowChargeDeduction = data[0].isDeductionChargeEnabled;
                    if (!allowChargeDeduction && $scope.$root.currentState === 'systemSetting.chargeItem.deductionPlan') {
                        $scope.$root.currentState = 'systemSetting.chargeItem.chargeCategory';
                        _this.appNav.goToState($scope.$root.currentState);
                    }
                    var hasFreeFields = data[1] && data[1].length;
                    var states = [
                        new _this.appNav.TabItem('systemSetting.chargeItem.setting', '收费项目设置', '', 'setting.chargeitemBrowse'),
                        new _this.appNav.TabItem('systemSetting.chargeItem.import', '收费项导入', '', 'dataImport.chargeItem'),
                    ];
                    if (hasFreeFields) {
                        states.push(new _this.appNav.TabItem('systemSetting.chargeItem.freefield', '收费项目自由项配置', '', 'setting.chargeitemBrowse'));
                    }
                    states = states.concat([
                        new _this.appNav.TabItem('systemSetting.chargeItem.chargeType', '费用类型配置', '', 'setting.chargeitemBrowse'),
                        new _this.appNav.TabItem('systemSetting.chargeItem.chargeCategory', '收费类别配置', '', 'setting.chargeitemBrowse'),
                    ]);
                    if (allowChargeDeduction) {
                        states.push(new _this.appNav.TabItem('systemSetting.chargeItem.deductionPlan', '划扣方案设置', '', 'setting.chargeitemBrowse'));
                    }
                    states.push(new _this.appNav.TabItem('systemSetting.chargeItem.chargePackageSetting', '收费套餐设置', '', 'setting.chargeitemBrowse')),
                        $scope.states = states;
                });
            };
        }
        Ares3SystemSettingChargeItemPage.$inject = ['appNav', 'dataDicSvc', '$q'];
        return Ares3SystemSettingChargeItemPage;
    }());
    systemSettingModule.directive('ares3SystemSettingChargeItemPage', Ares.tsDirective(Ares3SystemSettingChargeItemPage));
})(systemSetting || (systemSetting = {}));

var systemSetting;
(function (systemSetting) {
    var Ares3SystemSettingChargePackagePage = /** @class */ (function () {
        function Ares3SystemSettingChargePackagePage(appNav, moduleOptionProvider) {
            var _this = this;
            this.appNav = appNav;
            this.moduleOptionProvider = moduleOptionProvider;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\">\n                <ares-tab states=\"states\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope) {
                var TabItem = _this.appNav.TabItem;
                $scope.states = [
                    new _this.appNav.TabItem('systemSetting.chargeItem.chargePackageSetting', '收费套餐设置', '', 'setting.chargeitemBrowse'),
                ];
            };
        }
        Ares3SystemSettingChargePackagePage.$inject = ['appNav', 'moduleOptionProvider'];
        return Ares3SystemSettingChargePackagePage;
    }());
    systemSettingModule.directive('ares3SystemSettingChargePackagePage', Ares.tsDirective(Ares3SystemSettingChargePackagePage));
})(systemSetting || (systemSetting = {}));

var systemSetting;
(function (systemSetting) {
    var Ares3SystemSettingChargePaymentPage = /** @class */ (function () {
        function Ares3SystemSettingChargePaymentPage(appNav, dataDicSvc, chargeSvc) {
            var _this = this;
            this.appNav = appNav;
            this.dataDicSvc = dataDicSvc;
            this.chargeSvc = chargeSvc;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\">\n                <ares-tab states=\"states\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope) {
                var checkVisibleLcPayGateway = function () {
                    return $scope.isLcPayGatewayVisible;
                };
                var initSystemConfig = function () {
                    _this.dataDicSvc.officeSettingDic.load().then(function (data) {
                        $scope.isLcPayGatewayVisible = data.isLcPayGatewayVisible;
                    });
                };
                var initStates = function () {
                    _this.chargeSvc.getThirdPartyPayConfig().success(function (data) {
                        var thirdPartyDeviceVisible = data && data.length > 0;
                        var states = [
                            new _this.appNav.TabItem('systemSetting.chargePayment.method', '支付方式配置', '', 'setting.chargeitemBrowse'),
                            new _this.appNav.TabItem('systemSetting.chargePayment.lcPayGateway', '领健在线收银配置', '', 'setting.chargeitemBrowse', null, checkVisibleLcPayGateway),
                        ];
                        if (thirdPartyDeviceVisible) {
                            states.push(new _this.appNav.TabItem('systemSetting.chargePayment.thirdPartyDevices', '收银设备管理', '', ''));
                        }
                        $scope.states = states;
                    });
                };
                (function initialize() {
                    initSystemConfig();
                    initStates();
                })();
            };
        }
        Ares3SystemSettingChargePaymentPage.$inject = ['appNav', 'dataDicSvc', 'chargeSvc'];
        return Ares3SystemSettingChargePaymentPage;
    }());
    systemSettingModule.directive('ares3SystemSettingChargePaymentPage', Ares.tsDirective(Ares3SystemSettingChargePaymentPage));
})(systemSetting || (systemSetting = {}));

var systemSetting;
(function (systemSetting) {
    var Ares3SystemSettingMarketingMemberPointPage = /** @class */ (function () {
        function Ares3SystemSettingMarketingMemberPointPage(appNav, moduleOptionProvider) {
            var _this = this;
            this.appNav = appNav;
            this.moduleOptionProvider = moduleOptionProvider;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\">\n                <ares-tab states=\"states\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope) {
                var TabItem = _this.appNav.TabItem;
                $scope.states = [
                    new TabItem('systemSetting.memberPoint.management', '积分规则', '', 'membership.point'),
                ];
            };
        }
        Ares3SystemSettingMarketingMemberPointPage.$inject = ['appNav', 'moduleOptionProvider'];
        return Ares3SystemSettingMarketingMemberPointPage;
    }());
    systemSettingModule.directive('ares3SystemSettingMarketingMemberPointPage', Ares.tsDirective(Ares3SystemSettingMarketingMemberPointPage));
})(systemSetting || (systemSetting = {}));

var systemSetting;
(function (systemSetting) {
    var Ares3SystemSettingMarketingMemberTypesPage = /** @class */ (function () {
        function Ares3SystemSettingMarketingMemberTypesPage(appNav, moduleOptionProvider) {
            var _this = this;
            this.appNav = appNav;
            this.moduleOptionProvider = moduleOptionProvider;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\">\n                <ares-tab states=\"states\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope) {
                var TabItem = _this.appNav.TabItem;
                $scope.states = [
                    new TabItem('systemSetting.memberTypes.management', '会员类型设置', '', 'membership.categroy'),
                    new TabItem('systemSetting.memberTypes.cardNumberConfig', '会员卡号设置', '', 'setting.office'),
                    new TabItem('systemSetting.memberTypes.point', '积分规则', '', 'membership.point'),
                ];
            };
        }
        Ares3SystemSettingMarketingMemberTypesPage.$inject = ['appNav', 'moduleOptionProvider'];
        return Ares3SystemSettingMarketingMemberTypesPage;
    }());
    systemSettingModule.directive('ares3SystemSettingMarketingMemberTypesPage', Ares.tsDirective(Ares3SystemSettingMarketingMemberTypesPage));
})(systemSetting || (systemSetting = {}));

var systemSetting;
(function (systemSetting) {
    var Ares3SystemSettingMarketingReferralPage = /** @class */ (function () {
        function Ares3SystemSettingMarketingReferralPage(appNav, moduleOptionProvider) {
            var _this = this;
            this.appNav = appNav;
            this.moduleOptionProvider = moduleOptionProvider;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\">\n                <ares-tab states=\"states\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope) {
                var TabItem = _this.appNav.TabItem;
                var states = [
                    new TabItem('systemSetting.marketingReferral.arrival', '到店激励', '', null),
                ];
                if (_this.moduleOptionProvider.isReferralPaymentRuleEnabled()) {
                    states.push(new TabItem('systemSetting.marketingReferral.payment', '单笔消费激励', '', null));
                    states.push(new TabItem('systemSetting.marketingReferral.totalPayment', '累计消费激励', '', null));
                }
                $scope.states = states;
            };
        }
        Ares3SystemSettingMarketingReferralPage.$inject = ['appNav', 'moduleOptionProvider'];
        return Ares3SystemSettingMarketingReferralPage;
    }());
    systemSettingModule.directive('ares3SystemSettingMarketingReferralPage', Ares.tsDirective(Ares3SystemSettingMarketingReferralPage));
})(systemSetting || (systemSetting = {}));

var systemSetting;
(function (systemSetting) {
    var Ares3SystemSettingMedicalCheckPage = /** @class */ (function () {
        function Ares3SystemSettingMedicalCheckPage(appNav, moduleOptionProvider) {
            var _this = this;
            this.appNav = appNav;
            this.moduleOptionProvider = moduleOptionProvider;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\">\n                <ares-tab states=\"states\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope) {
                var TabItem = _this.appNav.TabItem;
                $scope.states = [
                    new TabItem('systemSetting.medicalCheck.category', '检查大类', '', 'medicalExam.category'),
                    new TabItem('systemSetting.medicalCheck.item', '检查项目', '', 'medicalExam.item'),
                ];
            };
        }
        Ares3SystemSettingMedicalCheckPage.$inject = ['appNav', 'moduleOptionProvider'];
        return Ares3SystemSettingMedicalCheckPage;
    }());
    systemSettingModule.directive('ares3SystemSettingMedicalCheckPage', Ares.tsDirective(Ares3SystemSettingMedicalCheckPage));
})(systemSetting || (systemSetting = {}));

var systemSetting;
(function (systemSetting) {
    var Ares3SystemSettingMedicalDiagnosisPage = /** @class */ (function () {
        function Ares3SystemSettingMedicalDiagnosisPage(appNav, loginContext) {
            var _this = this;
            this.appNav = appNav;
            this.loginContext = loginContext;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\">\n                <ares-tab states=\"states\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope) {
                var TabItem = _this.appNav.TabItem;
                var states = [
                    new TabItem('systemSetting.medicalDiagnosis.management', '诊断项目', '', 'setting.diagnosis'),
                ];
                if (!_this.loginContext.isProfessional) {
                    states.push(new TabItem('systemSetting.medicalDiagnosis.treatmentPlan', '治疗计划项目配置', '', 'setting.appointment'));
                }
                $scope.states = states;
            };
        }
        Ares3SystemSettingMedicalDiagnosisPage.$inject = ['appNav', 'loginContext'];
        return Ares3SystemSettingMedicalDiagnosisPage;
    }());
    systemSettingModule.directive('ares3SystemSettingMedicalDiagnosisPage', Ares.tsDirective(Ares3SystemSettingMedicalDiagnosisPage));
})(systemSetting || (systemSetting = {}));

var systemSetting;
(function (systemSetting) {
    var Ares3SystemSettingMedicalRecordPage = /** @class */ (function () {
        function Ares3SystemSettingMedicalRecordPage(appNav, moduleOptionProvider) {
            var _this = this;
            this.appNav = appNav;
            this.moduleOptionProvider = moduleOptionProvider;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\">\n                <ares-tab states=\"states\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope) {
                var TabItem = _this.appNav.TabItem;
                $scope.states = [
                    new TabItem('systemSetting.medicalRecord.settings', '病历配置', '', 'setting.emrtemplate'),
                    new TabItem('systemSetting.medicalRecord.template', '病历模板', '', 'setting.emrtemplate'),
                    new TabItem('systemSetting.medicalRecord.templateItem', '词条配置', '', 'setting.emrtemplate'),
                ];
            };
        }
        Ares3SystemSettingMedicalRecordPage.$inject = ['appNav', 'moduleOptionProvider'];
        return Ares3SystemSettingMedicalRecordPage;
    }());
    systemSettingModule.directive('ares3SystemSettingMedicalRecordPage', Ares.tsDirective(Ares3SystemSettingMedicalRecordPage));
})(systemSetting || (systemSetting = {}));

var systemSetting;
(function (systemSetting) {
    var Ares3SystemSettingBusinessManagementPage = /** @class */ (function () {
        function Ares3SystemSettingBusinessManagementPage(appNav, moduleOptionProvider) {
            var _this = this;
            this.appNav = appNav;
            this.moduleOptionProvider = moduleOptionProvider;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\">\n                <ares-tab states=\"states\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope) {
                var TabItem = _this.appNav.TabItem;
                $scope.states = [
                    new TabItem('systemSetting.businessManagement.approvalSetting', '审批管理设置', '', 'setting.approval')
                ];
            };
        }
        Ares3SystemSettingBusinessManagementPage.$inject = ['appNav', 'moduleOptionProvider'];
        return Ares3SystemSettingBusinessManagementPage;
    }());
    systemSettingModule.directive('ares3SystemSettingBusinessManagementPage', Ares.tsDirective(Ares3SystemSettingBusinessManagementPage));
})(systemSetting || (systemSetting = {}));

var systemSetting;
(function (systemSetting) {
    var Ares3SystemSettingDentalLabPage = /** @class */ (function () {
        function Ares3SystemSettingDentalLabPage(appNav, moduleOptionProvider) {
            var _this = this;
            this.appNav = appNav;
            this.moduleOptionProvider = moduleOptionProvider;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\">\n                <ares-tab states=\"states\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope) {
                var TabItem = _this.appNav.TabItem;
                $scope.states = [
                    new TabItem('systemSetting.dentalLab.settings', '技加工配置', '', 'patientOutProcess.config'),
                ];
            };
        }
        Ares3SystemSettingDentalLabPage.$inject = ['appNav', 'moduleOptionProvider'];
        return Ares3SystemSettingDentalLabPage;
    }());
    systemSettingModule.directive('ares3SystemSettingDentalLabPage', Ares.tsDirective(Ares3SystemSettingDentalLabPage));
})(systemSetting || (systemSetting = {}));

var systemSetting;
(function (systemSetting) {
    var Ares3SystemSettingOfficeInfoPage = /** @class */ (function () {
        function Ares3SystemSettingOfficeInfoPage(appNav, moduleOptionProvider) {
            var _this = this;
            this.appNav = appNav;
            this.moduleOptionProvider = moduleOptionProvider;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\">\n                <ares-tab states=\"states\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope) {
                var TabItem = _this.appNav.TabItem;
                $scope.states = [
                    new _this.appNav.TabItem('systemSetting.officeManagementMisc.invoice', '诊所发票信息', '', 'setting.office'),
                    new _this.appNav.TabItem('systemSetting.officeManagementMisc.operatory', '诊室设置', '', 'setting.operatory'),
                ];
            };
        }
        Ares3SystemSettingOfficeInfoPage.$inject = ['appNav', 'moduleOptionProvider'];
        return Ares3SystemSettingOfficeInfoPage;
    }());
    systemSettingModule.directive('ares3SystemSettingOfficeInfoPage', Ares.tsDirective(Ares3SystemSettingOfficeInfoPage));
})(systemSetting || (systemSetting = {}));

/**
 * 把hebe页面简单地包一层，用作tab下的ui-view
 */
var systemSetting;
(function (systemSetting) {
    'use strict';
    var Ares3SystemSettingOfficeManagementCheckInSettingView = /** @class */ (function () {
        function Ares3SystemSettingOfficeManagementCheckInSettingView() {
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div style=\"width: 100%; height: 100%;\">\n                <ares-new-home-view target-route=\"officeSettings.checkInSetting\"></ares-new-home-view>\n            </div>\n        ";
        }
        Ares3SystemSettingOfficeManagementCheckInSettingView.$inject = [];
        return Ares3SystemSettingOfficeManagementCheckInSettingView;
    }());
    systemSettingModule.directive('ares3SystemSettingOfficeManagementCheckInSettingView', Ares.tsDirective(Ares3SystemSettingOfficeManagementCheckInSettingView));
})(systemSetting || (systemSetting = {}));

var systemSetting;
(function (systemSetting) {
    var Ares3SystemSettingOfficeManagementMiscPage = /** @class */ (function () {
        function Ares3SystemSettingOfficeManagementMiscPage(appNav, loginContext, officeOptionSvc) {
            var _this = this;
            this.appNav = appNav;
            this.loginContext = loginContext;
            this.officeOptionSvc = officeOptionSvc;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\">\n                <ares-tab states=\"states\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope) {
                var TabItem = _this.appNav.TabItem;
                var states = [];
                if (_this.loginContext.isRoot) {
                    states.push(new TabItem('systemSetting.officeManagementMisc.permissionSetting', '总部业务设置', '', null));
                }
                states = states.concat([
                    new TabItem('systemSetting.officeManagementMisc.businessRule', '业务规则设置', '', 'setting.office&settings.rule'),
                    new TabItem('systemSetting.officeManagementMisc.systemSetting', '基础项目', '', 'setting.systemsetting'),
                    new TabItem('systemSetting.officeManagementMisc.freefieldSetting', '自由项配置', '', 'setting.office'),
                    new TabItem('systemSetting.officeManagementMisc.operatory', '诊室设置', '', 'setting.operatory'),
                    new TabItem('systemSetting.officeManagementMisc.invoice', '诊所发票信息', '', 'setting.office')
                ]);
                _this.officeOptionSvc.getOfficeOption(_this.officeOptionSvc.optionKeys.IsShangbaoEnabled).then(function (isShangbaoEnabled) {
                    if (isShangbaoEnabled) {
                        states.push(new TabItem('systemSetting.officeManagementMisc.shangbao', '商保配置', '', 'setting.office&settings.healthInsuranceConfig'));
                    }
                    $scope.states = states;
                });
            };
        }
        Ares3SystemSettingOfficeManagementMiscPage.$inject = ['appNav', 'loginContext', 'officeOptionSvc'];
        return Ares3SystemSettingOfficeManagementMiscPage;
    }());
    systemSettingModule.directive('ares3SystemSettingOfficeManagementMiscPage', Ares.tsDirective(Ares3SystemSettingOfficeManagementMiscPage));
})(systemSetting || (systemSetting = {}));

var systemSetting;
(function (systemSetting) {
    var Ares3SystemSettingSmsManagementPage = /** @class */ (function () {
        function Ares3SystemSettingSmsManagementPage(appNav, moduleOptionProvider) {
            var _this = this;
            this.appNav = appNav;
            this.moduleOptionProvider = moduleOptionProvider;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\">\n                <ares-tab states=\"states\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope) {
                var TabItem = _this.appNav.TabItem;
                $scope.states = [
                    new TabItem('officeManagement.sms.autoRule', '短信自动发送', '', 'shortMessage.charge'),
                ];
            };
        }
        Ares3SystemSettingSmsManagementPage.$inject = ['appNav', 'moduleOptionProvider'];
        return Ares3SystemSettingSmsManagementPage;
    }());
    systemSettingModule.directive('ares3SystemSettingSmsManagementPage', Ares.tsDirective(Ares3SystemSettingSmsManagementPage));
})(systemSetting || (systemSetting = {}));

var systemSetting;
(function (systemSetting) {
    var Ares3SystemSettingStaffManagementPage = /** @class */ (function () {
        function Ares3SystemSettingStaffManagementPage(appNav, moduleOptionProvider) {
            var _this = this;
            this.appNav = appNav;
            this.moduleOptionProvider = moduleOptionProvider;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\">\n                <ares-tab states=\"states\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope) {
                var TabItem = _this.appNav.TabItem;
                $scope.states = [
                    new _this.appNav.TabItem('systemSetting.staffManagement.scheduleSetting', '班次配置', '', 'schedule.rule'),
                    new _this.appNav.TabItem('systemSetting.staffManagement.attendanceSetting', '考勤配置', '', 'schedule.attendanceConfig'),
                ];
            };
        }
        Ares3SystemSettingStaffManagementPage.$inject = ['appNav', 'moduleOptionProvider'];
        return Ares3SystemSettingStaffManagementPage;
    }());
    systemSettingModule.directive('ares3SystemSettingStaffManagementPage', Ares.tsDirective(Ares3SystemSettingStaffManagementPage));
})(systemSetting || (systemSetting = {}));

/**
 * 把hebe页面简单地包一层，用作tab下的ui-view
 */
var management;
(function (management) {
    'use strict';
    var Ares3OfficeManagementRoleSettingView = /** @class */ (function () {
        function Ares3OfficeManagementRoleSettingView() {
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div style=\"width: 100%; height: 100%;\">\n                <ares-new-home-view target-route=\"systemSetting.provider.role\"></ares-new-home-view>\n            </div>\n        ";
        }
        Ares3OfficeManagementRoleSettingView.$inject = [];
        return Ares3OfficeManagementRoleSettingView;
    }());
    managementModule.directive('ares3OfficeManagementRoleSettingView', Ares.tsDirective(Ares3OfficeManagementRoleSettingView));
})(management || (management = {}));

var systemSetting;
(function (systemSetting) {
    var Ares3SystemSettingPatientConsultantPage = /** @class */ (function () {
        function Ares3SystemSettingPatientConsultantPage(appNav, officeOptionSvc) {
            var _this = this;
            this.appNav = appNav;
            this.officeOptionSvc = officeOptionSvc;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\">\n                <ares-tab states=\"states\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope) {
                var TabItem = _this.appNav.TabItem;
                $scope.states = [
                    new TabItem('systemSetting.patientConsultant.intention', '成交意愿', '', 'consultCenter.willingParties'),
                ];
            };
        }
        Ares3SystemSettingPatientConsultantPage.$inject = ['appNav', 'officeOptionSvc'];
        return Ares3SystemSettingPatientConsultantPage;
    }());
    systemSettingModule.directive('ares3SystemSettingPatientConsultantPage', Ares.tsDirective(Ares3SystemSettingPatientConsultantPage));
})(systemSetting || (systemSetting = {}));

var systemSetting;
(function (systemSetting) {
    var Ares3SystemSettingPatientFieldPage = /** @class */ (function () {
        function Ares3SystemSettingPatientFieldPage(appNav, officeOptionSvc) {
            var _this = this;
            this.appNav = appNav;
            this.officeOptionSvc = officeOptionSvc;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\">\n                <ares-tab states=\"states\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope) {
                var TabItem = _this.appNav.TabItem;
                $scope.states = [
                    new TabItem('systemSetting.patientField.newPatient', '新建患者必填项', '', 'setting.office&settings.newPatientInfo'),
                    new TabItem('systemSetting.patientField.onlineConsultant', '网电新建患者必填项', '', 'setting.office&settings.onlineConsultCreateInfo'),
                    new TabItem('systemSetting.patientField.checkInSetting', '挂号必填项设置', '', 'setting.office&settings.checkInInfo'),
                ];
            };
        }
        Ares3SystemSettingPatientFieldPage.$inject = ['appNav', 'officeOptionSvc'];
        return Ares3SystemSettingPatientFieldPage;
    }());
    systemSettingModule.directive('ares3SystemSettingPatientFieldPage', Ares.tsDirective(Ares3SystemSettingPatientFieldPage));
})(systemSetting || (systemSetting = {}));

var systemSetting;
(function (systemSetting) {
    var Ares3SystemSettingPatientFollowupPage = /** @class */ (function () {
        function Ares3SystemSettingPatientFollowupPage(appNav, officeOptionSvc) {
            var _this = this;
            this.appNav = appNav;
            this.officeOptionSvc = officeOptionSvc;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\">\n                <ares-tab states=\"states\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope) {
                var TabItem = _this.appNav.TabItem;
                $scope.states = [
                    new TabItem('systemSetting.patientFollowup.template', '随访模板', '', 'followup.config'),
                    new TabItem('systemSetting.patientFollowup.contentTemplate', '随访内容模板', '', 'followup.content'),
                    new TabItem('systemSetting.patientFollowup.resultTemplate', '随访结果模板', '', 'followup.result'),
                    new TabItem('systemSetting.patientFollowup.autoRule', '自动随访规则', '', 'followup.rule'),
                ];
            };
        }
        Ares3SystemSettingPatientFollowupPage.$inject = ['appNav', 'officeOptionSvc'];
        return Ares3SystemSettingPatientFollowupPage;
    }());
    systemSettingModule.directive('ares3SystemSettingPatientFollowupPage', Ares.tsDirective(Ares3SystemSettingPatientFollowupPage));
})(systemSetting || (systemSetting = {}));

var systemSetting;
(function (systemSetting) {
    var Ares3SystemSettingPatientRevisitPage = /** @class */ (function () {
        function Ares3SystemSettingPatientRevisitPage(appNav, officeOptionSvc) {
            var _this = this;
            this.appNav = appNav;
            this.officeOptionSvc = officeOptionSvc;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\">\n                <ares-tab states=\"states\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope) {
                var TabItem = _this.appNav.TabItem;
                $scope.states = [
                    new TabItem('systemSetting.patientRevisit.autoRule', '自动回访规则', '', 'patientMgmt.autoRevisitRule'),
                ];
            };
        }
        Ares3SystemSettingPatientRevisitPage.$inject = ['appNav', 'officeOptionSvc'];
        return Ares3SystemSettingPatientRevisitPage;
    }());
    systemSettingModule.directive('ares3SystemSettingPatientRevisitPage', Ares.tsDirective(Ares3SystemSettingPatientRevisitPage));
})(systemSetting || (systemSetting = {}));

var systemSetting;
(function (systemSetting) {
    var Ares3SystemSettingPatientTagPage = /** @class */ (function () {
        function Ares3SystemSettingPatientTagPage(appNav, officeOptionSvc) {
            var _this = this;
            this.appNav = appNav;
            this.officeOptionSvc = officeOptionSvc;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\">\n                <ares-tab states=\"states\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope) {
                var TabItem = _this.appNav.TabItem;
                $scope.states = [
                    new TabItem('systemSetting.patientTag.management', '标签设置', '', 'managementCenter.tagCenter'),
                ];
            };
        }
        Ares3SystemSettingPatientTagPage.$inject = ['appNav', 'officeOptionSvc'];
        return Ares3SystemSettingPatientTagPage;
    }());
    systemSettingModule.directive('ares3SystemSettingPatientTagPage', Ares.tsDirective(Ares3SystemSettingPatientTagPage));
})(systemSetting || (systemSetting = {}));

var systemSetting;
(function (systemSetting) {
    var Ares3SystemSettingSupplychainRulePage = /** @class */ (function () {
        function Ares3SystemSettingSupplychainRulePage(appNav, moduleOptionProvider) {
            var _this = this;
            this.appNav = appNav;
            this.moduleOptionProvider = moduleOptionProvider;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\">\n                <ares-tab states=\"states\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope) {
                var TabItem = _this.appNav.TabItem;
                $scope.states = [
                    new TabItem('systemSetting.supplychainRule.management', '业务规则设置', '', 'setting.office&settings.supplychain'),
                ];
            };
        }
        Ares3SystemSettingSupplychainRulePage.$inject = ['appNav', 'moduleOptionProvider'];
        return Ares3SystemSettingSupplychainRulePage;
    }());
    systemSettingModule.directive('ares3SystemSettingSupplychainRulePage', Ares.tsDirective(Ares3SystemSettingSupplychainRulePage));
})(systemSetting || (systemSetting = {}));

var systemSetting;
(function (systemSetting) {
    var Ares3SystemSettingTriagePage = /** @class */ (function () {
        function Ares3SystemSettingTriagePage(appNav, moduleOptionProvider) {
            var _this = this;
            this.appNav = appNav;
            this.moduleOptionProvider = moduleOptionProvider;
            this.restrict = 'E';
            this.replace = true;
            this.template = "\n            <div class=\"ares3-page-wrapper\">\n                <ares-tab states=\"states\"></ares-tab>\n            </div>\n        ";
            this.link = function ($scope) {
                var TabItem = _this.appNav.TabItem;
                $scope.states = [
                    new TabItem('systemSetting.triage.calling', '叫号设置', '', 'setting.office'),
                    new TabItem('systemSetting.triage.checkInSetting', '挂号设置', '', 'setting.systemsetting'),
                ];
            };
        }
        Ares3SystemSettingTriagePage.$inject = ['appNav', 'moduleOptionProvider'];
        return Ares3SystemSettingTriagePage;
    }());
    systemSettingModule.directive('ares3SystemSettingTriagePage', Ares.tsDirective(Ares3SystemSettingTriagePage));
})(systemSetting || (systemSetting = {}));

